List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:com.trsst.Command.java
public int doPull(Client client, CommandLine commands, LinkedList<String> arguments, PrintStream out) { if (arguments.size() < 1) { printPullUsage();//from w ww.j av a2 s . c o m return 127; // "command not found" } // decryption option String id = commands.getOptionValue("d"); PrivateKey[] decryptionKeys = null; if (id != null) { // obtain password id = Common.toFeedIdString(id); char[] password = null; String pass = commands.getOptionValue("p"); if (pass != null) { password = pass.toCharArray(); } else { try { Console console = System.console(); if (console != null) { password = console.readPassword("Password: "); } else { log.info("No console detected for password input."); } } catch (Throwable t) { log.error("Unexpected error while reading password", t); } } if (password == null) { log.error("Password is required to decrypt."); return 127; // "command not found" } if (password.length < 6) { System.err.println("Password must be at least six characters in length."); return 127; // "command not found" } // obtain keys KeyPair signingKeys = null; KeyPair encryptionKeys = null; String keyPath = commands.getOptionValue("k"); File keyFile; if (keyPath != null) { keyFile = new File(keyPath, id + Common.KEY_EXTENSION); } else { keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION); } if (keyFile.exists()) { System.err.println("Using existing account id: " + id); } else { System.err.println("Cannot locate keys for account id: " + id); return 78; // "configuration error" } signingKeys = readSigningKeyPair(id, keyFile, password); if (signingKeys != null) { encryptionKeys = readEncryptionKeyPair(id, keyFile, password); if (encryptionKeys == null) { decryptionKeys = new PrivateKey[] { signingKeys.getPrivate() }; } else { decryptionKeys = new PrivateKey[] { encryptionKeys.getPrivate(), signingKeys.getPrivate() }; } } } List<String> ids = new LinkedList<String>(); for (String arg : arguments) { ids.add(arg); } for (String feedId : ids) { try { Object feed; if (decryptionKeys != null) { feed = client.pull(feedId, decryptionKeys); } else { feed = client.pull(feedId); } if (feed != null) { if (format) { out.println(Common.formatXML(feed.toString())); } else { out.println(feed.toString()); } } else { System.err.println("Could not fetch: " + feedId + " : " + client); } } catch (Throwable t) { log.error("Unexpected error on pull: " + feedId + " : " + client, t); } } return 0; // "OK" }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest in RA mode without filling the 'issuerDN' field in the request. * Successful operation is expected and a new certificate is received. * //from w ww . ja v a 2 s . c o m * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra) * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate' * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA' * - Pre-configuration: Set cmp.checkadminauthorization to 'true' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Verifies the signature of the CMP request * - Sends the request using HTTP and receives an response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Check that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Obtains the certificate from the response * - Checks that the obtained certificate has the right subjectDN and issuerDN * * @throws Exception */ @Test public void test09RANoIssuer() throws Exception { if (log.isTraceEnabled()) { log.trace("test11RANoIssuer()"); } this.cmpConfiguration.setRAMode(this.cmpAlias, true); this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA"); this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //------------------ create the user and issue his first certificate ------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN, null, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes())); assertNotNull("Failed to generate a CMP renewal request", req); CertReqMessages kur = (CertReqMessages) req.getBody().getContent(); int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123"); KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE"); Certificate admCert = getCertFromCredentials(admToken); CMPCertificate[] extraCert = getCMPCert(admCert); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); //send request and recieve response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId); assertNotNull("Failed to renew the certificate", cert); removeAuthenticationToken(admToken, admCert, "cmpTestAdmin"); if (log.isTraceEnabled()) { log.trace("<test11RANoIssuer()"); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest in RA mode when there are more than one authentication module configured. * Successful operation is expected and a new certificate is received. * // ww w . j av a 2s.c o m * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra) * - Pre-configuration: Sets the cmp.authenticationmodule to "HMAC;DnPartPwd;EndEntityCertificate" * - Pre-configuration: Sets the cmp.authenticationparameters to "-;OU;TestCA" * - Pre-configuration: Set cmp.checkadminauthorization to 'true' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Verifies the signature of the CMP request * - Sends the request using HTTP and receives an response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Check that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Obtains the certificate from the response * - Checks that the obtained certificate has the right subjectDN and issuerDN * * @throws Exception */ @Test public void test11RAMultipleAuthenticationModules() throws Exception { if (log.isTraceEnabled()) { log.trace("test13RAMultipleAuthenticationModules"); } this.cmpConfiguration.setRAMode(this.cmpAlias, true); String authmodules = CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_DN_PART_PWD + ";" + CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE; this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, authmodules); this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "-;OU;TestCA"); this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //------------------ create the user and issue his first certificate ------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN, null, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes())); assertNotNull("Failed to generate a CMP renewal request", req); CertReqMessages kur = (CertReqMessages) req.getBody().getContent(); int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123"); KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE"); Certificate admCert = getCertFromCredentials(admToken); CMPCertificate[] extraCert = getCMPCert(admCert); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); //send request and recieve response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId); assertNotNull("Failed to renew the certificate", cert); removeAuthenticationToken(admToken, admCert, "cmpTestAdmin"); if (log.isTraceEnabled()) { log.trace("<test13RAMultipleAuthenticationModules()"); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest in RA mode. * Successful operation is expected and a new certificate is received. * //from w ww . j a va 2s . co m * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra) * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate' * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA' * - Pre-configuration: Set cmp.checkadminauthorization to 'true' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Verifies the signature of the CMP request * - Sends the request using HTTP and receives an response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Check that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Obtains the certificate from the response * - Checks that the obtained certificate has the right subjectDN and issuerDN * * @throws Exception */ @Test public void test07RAMode() throws Exception { if (log.isTraceEnabled()) { log.trace("test09RAMode()"); } this.cmpConfiguration.setRAMode(this.cmpAlias, true); this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA"); this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //------------------ create the user and issue his first certificate ------------- createUser(this.username, this.userDN.toString(), "foo123"); final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final Certificate certificate; certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN, this.issuerDN, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes())); assertNotNull("Failed to generate a CMP renewal request", req); final CertReqMessages kur = (CertReqMessages) req.getBody().getContent(); int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123"); final KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE"); Certificate admCert = getCertFromCredentials(admToken); CMPCertificate[] extraCert = getCMPCert(admCert); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); //send request and recieve response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId); assertNotNull("Failed to renew the certificate", cert); removeAuthenticationToken(admToken, admCert, "cmpTestAdmin"); if (log.isTraceEnabled()) { log.trace("<test09RAMode()"); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest in RA mode with neither subjectDN nor issuerDN are set in the request. * A CMP error message is expected and no certificate renewal. * //from w w w . ja v a 2s . co m * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal) * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate' * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA' * - Pre-configuration: Set cmp.checkadminauthorization to 'true' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Verifies the signature of the CMP request * - Sends the request using HTTP and receives an response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Check that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Parse the response and make sure that the parsing did not result in a 'null' * - Check that the CMP response message tag number is '23', indicating a CMP error message * - Check that the CMP response message contain the expected error details text * * @throws Exception */ @Test public void test10RANoIssuerNoSubjectDN() throws Exception { if (log.isTraceEnabled()) { log.trace("test12RANoIssuerNoSubjetDN()"); } this.cmpConfiguration.setRAMode(this.cmpAlias, true); this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA"); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //------------------ create the user and issue his first certificate ------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes())); assertNotNull("Failed to generate a CMP renewal request", req); createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123"); KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE"); Certificate admCert = getCertFromCredentials(admToken); CMPCertificate[] extraCert = getCMPCert(admCert); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); //send request and recieve response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); final PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); final String expectedErrMsg = "Cannot find a SubjectDN in the request"; assertEquals(expectedErrMsg, errMsg); removeAuthenticationToken(admToken, admCert, "cmpTestAdmin"); if (log.isTraceEnabled()) { log.trace("<test12RANoIssuerNoSubjectDN()"); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest in RA mode when the authentication module is NOT set to 'EndEntityCertificate'. * A CMP error message is expected and no certificate renewal. * //from w w w . jav a 2 s. c o m * - Pre-configuration: Sets the operational mode to RA mode (cmp.raoperationalmode=ra) * - Pre-configuration: Sets the cmp.authenticationmodule to 'DnPartPwd' * - Pre-configuration: Sets the cmp.authenticationparameters to 'OU' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Verifies the signature of the CMP request * - Sends the request using HTTP and receives an response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Check that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Obtains the certificate from the response * - Checks that the obtained certificate has the right subjectDN and issuerDN * * @throws Exception */ @Test public void test12ECCNotSetInRA() throws Exception { if (log.isTraceEnabled()) { log.trace("test12ECCNotSetInRA()"); } this.cmpConfiguration.setRAMode(this.cmpAlias, true); this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, CmpConfiguration.AUTHMODULE_DN_PART_PWD); this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "OU"); this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, true); this.cmpConfiguration.setCMPDefaultCA(this.cmpAlias, ""); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //------------------ create the user and issue his first certificate ------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN, null, pAlg, null); assertNotNull("Failed to generate a CMP renewal request", req); createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123"); KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE"); final Certificate admCert = getCertFromCredentials(admToken); CMPCertificate[] extraCert = getCMPCert(admCert); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); //send request and recieve response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); final PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); final String expectedErrMsg = "EndEnityCertificate authentication module is not configured. For a KeyUpdate request to be authentication " + "in RA mode, EndEntityCertificate authentication module has to be set and configured"; assertEquals(expectedErrMsg, errMsg); removeAuthenticationToken(admToken, admCert, "cmpTestAdmin"); if (log.isTraceEnabled()) { log.trace("<test12ECCNotSetInRA()"); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest by an admin concerning a certificate of another EndEntity in client mode. * If the CA enforces unique public key, a CMP error message is expected and no certificate renewal. * If the CA does not enforce unique public key, a certificate will be renewed, though not the expected EndEntity certificate, but the admin certificate is renewed. * // ww w .jav a 2s. c om * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal) * - Pre-configuration: Sets the cmp.authenticationmodule to 'EndEntityCertificate' * - Pre-configuration: Sets the cmp.authenticationparameters to 'TestCA' * - Pre-configuration: Sets the cmp.allowautomatickeyupdate to 'true' * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful. * - Generates a CMP KeyUpdate Request and tests that such request has been created. * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null * - Verifies the signature of the CMP request * - Sends the request using HTTP and receives an response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Check that the signer is the expected CA * - Verifies the response signature * - Checks that the response's senderNonce is 16 bytes long * - Checks that the request's senderNonce is the same as the response's recipientNonce * - Checks that the request and the response has the same transactionID * - Obtains the certificate from the response * - Checks that the obtained certificate has the right subjectDN and issuerDN * * @throws Exception */ @Test public void test13AdminInClientMode() throws Exception { if (log.isTraceEnabled()) { log.trace("test09RAMode()"); } this.cmpConfiguration.setRAMode(this.cmpAlias, false); this.cmpConfiguration.setAuthenticationModule(this.cmpAlias, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(this.cmpAlias, "TestCA"); this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); //------------------ create the user and issue his first certificate ------------- createUser(this.username, this.userDN.toString(), "foo123"); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final Certificate certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, this.userDN, this.issuerDN, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes())); assertNotNull("Failed to generate a CMP renewal request", req); //int reqId = req.getBody().getKur().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); createUser("cmpTestAdmin", "CN=cmpTestAdmin,C=SE", "foo123"); KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken admToken = createAdminToken(admkeys, "cmpTestAdmin", "CN=cmpTestAdmin,C=SE"); Certificate admCert = getCertFromCredentials(admToken); CMPCertificate[] extraCert = getCMPCert(admCert); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); //send request and recieve response byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); CAInfo cainfo = this.caSession.getCAInfo(ADMIN, this.caid); if (cainfo.isDoEnforceUniquePublicKeys()) { final PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); final String expectedErrMsg = "User 'cmpTestAdmin' is not allowed to use same key as another user is using."; assertEquals(expectedErrMsg, errMsg); } else { PKIBody body = respObject.getBody(); int tag = body.getType(); assertEquals(8, tag); CertRepMessage c = (CertRepMessage) body.getContent(); assertNotNull(c); CMPCertificate cmpcert = c.getResponse()[0].getCertifiedKeyPair().getCertOrEncCert().getCertificate(); assertNotNull(cmpcert); X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded()); assertNotNull("Failed to renew the certificate", cert); assertEquals("CN=cmpTestAdmin, C=SE", cert.getSubjectX500Principal().toString()); } removeAuthenticationToken(admToken, admCert, "cmpTestAdmin"); if (log.isTraceEnabled()) { log.trace("<test09RAMode()"); } }
From source file:mitm.common.security.certificate.X509CertificateBuilderBulkTest.java
public void generateSelfSignedV3Certificate(Collection<X509Certificate> certificates) throws Exception { X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder(); String[] emails = generateRandomEmails(); //String[] emails = new String[]{"test@example.com", "test2@example.com"}; String cn = generateRandomCommonName(); issuerBuilder.setCommonName(cn);// w w w .j a v a2 s. c o m issuerBuilder.setCountryCode("NL"); issuerBuilder.setEmail(emails); issuerBuilder.setLocality("Amsterdam"); issuerBuilder.setState("NH"); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names(emails); X500Principal issuer = issuerBuilder.buildPrincipal(); GeneralNames altNames = altNamesBuider.buildAltNames(); Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>(); keyUsage.add(KeyUsageType.DIGITALSIGNATURE); keyUsage.add(KeyUsageType.KEYENCIPHERMENT); keyUsage.add(KeyUsageType.NONREPUDIATION); Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); BigInteger serialNumber = serialNumberGenerator.generate(); certificateBuilder.setSubject(issuer); certificateBuilder.setIssuer(issuer); certificateBuilder.setAltNames(altNames, true); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true); certificateBuilder.setNotBefore(DateUtils.addHours(new Date(), -1)); certificateBuilder.setNotAfter(DateUtils.addYears(new Date(), 20)); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm("SHA256WithRSAEncryption"); X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null); assertNotNull(certificate); certificates.add(certificate); }
From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java
@Test public void testSaveKeysToProviders01() throws ClassNotFoundException, IllegalAccessException, InstantiationException { String pn = "com.nicholaswilliams.mock"; RSAKeyPairGeneratorInterface.GeneratedClassDescriptor privateKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); privateKPDescriptor.setPackageName(pn); privateKPDescriptor.setClassName("TestPrivateKeyProvider01"); RSAKeyPairGeneratorInterface.GeneratedClassDescriptor publicKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); publicKPDescriptor.setPackageName(pn); publicKPDescriptor.setClassName("TestPublicKeyProvider01"); KeyPair keyPair = this.generator.generateKeyPair(); this.generator.saveKeyPairToProviders(keyPair, privateKPDescriptor, publicKPDescriptor, "testPassword01".toCharArray()); /////////////////////// assertNotNull("The private key code should not be null.", privateKPDescriptor.getJavaFileContents()); assertTrue("The private key code should have length.", privateKPDescriptor.getJavaFileContents().length() > 0); Class<?> privateKPClass = this .compileClass(pn + ".TestPrivateKeyProvider01", privateKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPrivateKeyProvider01"); PrivateKeyDataProvider privateKeyDataProvider = (PrivateKeyDataProvider) privateKPClass.newInstance(); assertNotNull("The private key data provider should not be null.", privateKeyDataProvider); byte[] privateKeyData = privateKeyDataProvider.getEncryptedPrivateKeyData(); assertNotNull("The private key data should not be null.", privateKeyData); assertTrue("The private key data should have length.", privateKeyData.length > 0); PrivateKey privateKey = KeyFileUtilities.readEncryptedPrivateKey(privateKeyData, "testPassword01".toCharArray()); assertNotNull("The private key should not be null.", privateKey); assertEquals("The private key is not correct.", keyPair.getPrivate(), privateKey); /////////////////////// assertNotNull("The public key code should not be null.", publicKPDescriptor.getJavaFileContents()); assertTrue("The public key code should have length.", publicKPDescriptor.getJavaFileContents().length() > 0); Class<?> publicKPClass = this .compileClass(pn + ".TestPublicKeyProvider01", publicKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPublicKeyProvider01"); PublicKeyDataProvider publicKeyDataProvider = (PublicKeyDataProvider) publicKPClass.newInstance(); assertNotNull("The public key data provider should not be null.", publicKeyDataProvider); byte[] publicKeyData = publicKeyDataProvider.getEncryptedPublicKeyData(); assertNotNull("The public key data should not be null.", publicKeyData); assertTrue("The public key data should have length.", publicKeyData.length > 0); PublicKey publicKey = KeyFileUtilities.readEncryptedPublicKey(publicKeyData, "testPassword01".toCharArray()); assertNotNull("The public key should not be null.", publicKey); assertEquals("The public key is not correct.", keyPair.getPublic(), publicKey); }
From source file:mitm.common.security.certificate.GenerateBulkPFX.java
private void generateCertificate(String email, String commonName, String alias) throws Exception { X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder(); subjectBuilder.setCommonName(commonName); subjectBuilder.setEmail(email);//w ww .j av a2 s . c om subjectBuilder.setCountryCode("NL"); subjectBuilder.setLocality("Amsterdam"); subjectBuilder.setState("NH"); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names(email); X500Principal subject = subjectBuilder.buildPrincipal(); GeneralNames altNames = altNamesBuider.buildAltNames(); Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>(); keyUsage.add(KeyUsageType.DIGITALSIGNATURE); keyUsage.add(KeyUsageType.KEYENCIPHERMENT); keyUsage.add(KeyUsageType.NONREPUDIATION); Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); BigInteger serialNumber = serialNumberGenerator.generate(); Date now = new Date(); certificateBuilder.setSubject(subject); certificateBuilder.setAltNames(altNames, true); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false); certificateBuilder.setNotBefore(now); certificateBuilder.setNotAfter(DateUtils.addYears(now, 20)); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption"); certificateBuilder.addSubjectKeyIdentifier(true); X509Certificate certificate = certificateBuilder.generateCertificate(caPrivateKey, caCertificate); assertNotNull(certificate); Certificate[] chain = new Certificate[] { certificate, caCertificate, rootCertificate }; keyStore.setKeyEntry(alias, keyPair.getPrivate(), null, chain); }