List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
/** * Generates a self-signed certificate based on the keypair and saves it in the keystore. * Should only be used to init the CA.// w ww. jav a 2 s . c o m */ public void initCA(String rootCertX500Name, String mcidregCertX500Name, String crlUrl, String ocspUrl, String outputCaCrlPath) { if (KEYSTORE_PASSWORD == null) { KEYSTORE_PASSWORD = "changeit"; } if (ROOT_KEYSTORE_PATH == null) { ROOT_KEYSTORE_PATH = "mc-root-keystore.jks"; } if (INTERMEDIATE_KEYSTORE_PATH == null) { INTERMEDIATE_KEYSTORE_PATH = "mc-it-keystore.jks"; } if (TRUSTSTORE_PASSWORD == null) { TRUSTSTORE_PASSWORD = "changeit"; } if (TRUSTSTORE_PATH == null) { TRUSTSTORE_PATH = "mc-truststore.jks"; } if (CRL_URL == null) { CRL_URL = crlUrl; } if (OCSP_URL == null) { OCSP_URL = ocspUrl; } KeyPair cakp = generateKeyPair(); KeyPair imkp = generateKeyPair(); KeyStore rootks = null; KeyStore itks; KeyStore ts; FileOutputStream rootfos = null; FileOutputStream itfos = null; FileOutputStream tsfos = null; try { rootks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); itks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() itks.load(null, KEYSTORE_PASSWORD.toCharArray()); // Store away the keystore. rootfos = new FileOutputStream(ROOT_KEYSTORE_PATH); itfos = new FileOutputStream(INTERMEDIATE_KEYSTORE_PATH); X509Certificate cacert; try { cacert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), cakp.getPublic(), new X500Name(rootCertX500Name), new X500Name(rootCertX500Name), null, "ROOTCA"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } X509Certificate imcert; try { imcert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), imkp.getPublic(), new X500Name(rootCertX500Name), new X500Name(mcidregCertX500Name), null, "INTERMEDIATE"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } Certificate[] certChain = new Certificate[1]; certChain[0] = cacert; rootks.setKeyEntry(ROOT_CERT_ALIAS, cakp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); rootks.store(rootfos, KEYSTORE_PASSWORD.toCharArray()); rootks = KeyStore.getInstance(KeyStore.getDefaultType()); rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); certChain = new Certificate[2]; certChain[0] = imcert; certChain[1] = cacert; itks.setKeyEntry(INTERMEDIATE_CERT_ALIAS, imkp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); itks.store(itfos, KEYSTORE_PASSWORD.toCharArray()); // Store away the truststore. ts = KeyStore.getInstance(KeyStore.getDefaultType()); ts.load(null, TRUSTSTORE_PASSWORD.toCharArray()); tsfos = new FileOutputStream(TRUSTSTORE_PATH); ts.setCertificateEntry(ROOT_CERT_ALIAS, cacert); ts.setCertificateEntry(INTERMEDIATE_CERT_ALIAS, imcert); ts.store(tsfos, TRUSTSTORE_PASSWORD.toCharArray()); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { safeClose(rootfos); safeClose(itfos); safeClose(tsfos); KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( KEYSTORE_PASSWORD.toCharArray()); PrivateKeyEntry rootCertEntry; try { rootCertEntry = (PrivateKeyEntry) rootks.getEntry(ROOT_CERT_ALIAS, protParam); generateRootCACRL(rootCertX500Name, null, rootCertEntry, outputCaCrlPath); } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { // todo, I think is an irrecoverable state, but we should not throw exception from finally, perhaps this code should not be in a finally block log.error("unable to generate RootCACRL", e); } } }
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);//from ww w.j av a 2 s.co 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:com.netscape.cmsutil.crypto.CryptoUtil.java
public static PKCS10 createCertificationRequest(String subjectName, KeyPair keyPair, Extensions exts) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IOException, CertificateException, SignatureException { String method = "CryptoUtil: createCertificationRequest: "; String alg = "SHA256withRSA"; PublicKey pubk = keyPair.getPublic(); X509Key key = convertPublicKeyToX509Key(pubk); if (pubk instanceof RSAPublicKey) { alg = "SHA256withRSA"; } else if (isECCKey(key)) { alg = "SHA256withEC"; } else {//from w ww .ja v a2 s .co m throw new NoSuchAlgorithmException(method + alg); } return createCertificationRequest(subjectName, key, (org.mozilla.jss.crypto.PrivateKey) keyPair.getPrivate(), alg, exts); }
From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java
private void generateAndStorePersonalInfo(SQLiteDatabase db) { String email = getUserEmail(); String name = email; // How to get this? KeyPair keypair = DBIdentityProvider.generateKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); String pubKeyStr = FastBase64.encodeToString(publicKey.getEncoded()); String privKeyStr = FastBase64.encodeToString(privateKey.getEncoded()); ContentValues cv = new ContentValues(); cv.put(MyInfo.PUBLIC_KEY, pubKeyStr); cv.put(MyInfo.PRIVATE_KEY, privKeyStr); cv.put(MyInfo.NAME, name);//from ww w . j a v a2 s . co m cv.put(MyInfo.EMAIL, email); db.insertOrThrow(MyInfo.TABLE, null, cv); Log.d(TAG, "Generated public key: " + pubKeyStr); Log.d(TAG, "Generated priv key: **************"); }
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. * //w w w . j a v a 2 s .com * - 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. * /*from w ww. j av a2 s . 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 and the request sender is not an authorized administrator. * A CMP error message is expected and no certificate renewal. * //w w w . j av a2s .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 test08RAModeNonAdmin() throws Exception { if (log.isTraceEnabled()) { log.trace("test10RAModeNonAdmin()"); } 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, this.userDN, this.issuerDN, pAlg, new DEROctetString("CMPTESTPROFILE".getBytes())); assertNotNull("Failed to generate a CMP renewal request", req); CMPCertificate[] extraCert = getCMPCert(certificate); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.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 = "'" + this.userDN + "' is not an authorized administrator."; assertEquals(expectedErrMsg, errMsg); if (log.isTraceEnabled()) { log.trace("<test10RAModeNonAdmin()"); } }
From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java
@Test public void testSaveKeyPairToFiles01() throws IOException { KeyPair keyPair = this.generator.generateKeyPair(); File file1 = new File("testSaveKeyPairToFiles01.private"); File file2 = new File("testSaveKeyPairToFiles01.public"); if (file1.exists()) FileUtils.forceDelete(file1);//from www .j a v a2s .co m if (file2.exists()) FileUtils.forceDelete(file2); assertFalse("File 1 should not exist.", file1.exists()); assertFalse("File 2 should not exist.", file2.exists()); this.generator.saveKeyPairToFiles(keyPair, "testSaveKeyPairToFiles01.private", "testSaveKeyPairToFiles01.public", "testMyPassword01".toCharArray()); assertTrue("File 1 should exist.", file1.exists()); assertTrue("File 2 should exist.", file2.exists()); PrivateKey privateKey = KeyFileUtilities.readEncryptedPrivateKey(file1, "testMyPassword01".toCharArray()); PublicKey publicKey = KeyFileUtilities.readEncryptedPublicKey(file2, "testMyPassword01".toCharArray()); assertNotNull("The private key should not be null.", privateKey); assertEquals("The private key is not correct.", keyPair.getPrivate(), privateKey); assertNotNull("The public key should not be null.", publicKey); assertEquals("The public key is not correct.", keyPair.getPublic(), publicKey); FileUtils.forceDelete(file1); FileUtils.forceDelete(file2); }
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 ww.j ava 2 s .c o 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. * // w ww. j a va 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()"); } }