List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest with a different key and the configurations is NOT to allow the use of the same keys. * Successful operation is expected and a new certificate is received. * //from w w w .j a va 2 s .c o m * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal) * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked. * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'false' * - 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 * - Sends the request using HTTP and receives a 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 test06UpdateWithDifferentKey() throws Exception { if (log.isTraceEnabled()) { log.trace(">test08UpdateWithDifferentKey"); } this.cmpConfiguration.setRAMode(this.cmpAlias, false); this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true); this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, false); 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; certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create a test certificate", certificate); KeyPair newkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, newkeys, false, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Failed to generate a CMP renewal request", req); CertReqMessages kur = (CertReqMessages) req.getBody().getContent(); int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); CMPCertificate[] extraCert = getCMPCert(certificate); req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(req); //******************************************'''''' final Signature sig = Signature.getInstance(req.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(certificate.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(req)); boolean verified = sig.verify(req.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive 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); assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(newkeys.getPublic())); assertFalse("The new certificate's keys are the same as the old certificate's keys.", cert.getPublicKey().equals(keys.getPublic())); if (log.isTraceEnabled()) { log.trace("<test08UpdateWithDifferentKey"); } }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
@Test public void test07SignedOcsp() throws Exception { assertTrue("This test can only be run on a full EJBCA installation.", ((HttpURLConnection) new URL(httpReqPath + '/').openConnection()).getResponseCode() == 200); // find a CA (TestCA?) create a user and generate his cert // send OCSP req to server and get good response // change status of cert to bad status // send OCSP req and get bad status // (send crap message and get good error) try {/*from w ww.j a v a2s . com*/ KeyPair keys = createUserCert(caid); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); X509CertificateHolder chain[] = new X509CertificateHolder[2]; chain[0] = new JcaX509CertificateHolder(ocspTestCert); chain[1] = new JcaX509CertificateHolder(cacert); gen.setRequestorName(chain[0].getSubject()); OCSPReq req = gen.build(new JcaContentSignerBuilder("SHA1WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), chain); // First test with a signed OCSP request that can be verified Collection<Certificate> cacerts = new ArrayList<Certificate>(); cacerts.add(cacert); CaCertificateCache certcache = CaCertificateCache.INSTANCE; certcache.loadCertificates(cacerts); X509Certificate signer = checkRequestSignature("127.0.0.1", req, certcache); assertNotNull(signer); assertEquals(ocspTestCert.getSerialNumber().toString(16), signer.getSerialNumber().toString(16)); // Try with an unsigned request, we should get a SignRequestException req = gen.build(); boolean caught = false; try { signer = checkRequestSignature("127.0.0.1", req, certcache); } catch (SignRequestException e) { caught = true; } assertTrue(caught); // sign with a keystore where the CA-certificate is not known KeyStore store = KeyStore.getInstance("PKCS12", "BC"); ByteArrayInputStream fis = new ByteArrayInputStream(ks3); store.load(fis, "foo123".toCharArray()); Certificate[] certs = KeyTools.getCertChain(store, "privateKey"); chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]); chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]); PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray()); req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480), chain); // Send the request and receive a singleResponse, this response should // throw an SignRequestSignatureException caught = false; try { signer = checkRequestSignature("127.0.0.1", req, certcache); } catch (SignRequestSignatureException e) { caught = true; } assertTrue(caught); // sign with a keystore where the signing certificate has expired store = KeyStore.getInstance("PKCS12", "BC"); fis = new ByteArrayInputStream(ksexpired); store.load(fis, "foo123".toCharArray()); certs = KeyTools.getCertChain(store, "ocspclient"); chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]); chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]); pk = (PrivateKey) store.getKey("ocspclient", "foo123".toCharArray()); req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480), chain); // Send the request and receive a singleResponse, this response should // throw an SignRequestSignatureException caught = false; try { signer = checkRequestSignature("127.0.0.1", req, certcache); } catch (SignRequestSignatureException e) { caught = true; } assertTrue(caught); } finally { endEntityManagementSession.deleteUser(admin, "ocsptest"); } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test06EERevReq() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); Collection<Certificate> certs = this.certificateStoreSession .findCertificatesBySubjectAndIssuer(USER_DN.toString(), issuerDN); log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\""); Certificate cert = null, tmp = null; Iterator<Certificate> itr = certs.iterator(); while (itr.hasNext()) { tmp = itr.next();/*from www.j a v a2 s. c om*/ if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) { cert = tmp; break; } } if (cert == null) { createUser("cmprevuser1", "CN=cmprevuser1,C=SE", "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); cert = this.signSession.createCertificate(ADMIN, "cmprevuser1", "foo123", new PublicKeyWrapper(admkeys.getPublic())); } assertNotNull("No certificate to revoke.", cert); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genRevReq(issuerDN, USER_DN, CertTools.getSerialNumber(cert), this.cacert, this.nonce, this.transid, false, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE", this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert)); assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED, revStatus); removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test07EERevReqWithUnknownCA() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); Collection<Certificate> certs = this.certificateStoreSession .findCertificatesBySubjectAndIssuer(USER_DN.toString(), issuerDN); log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\""); Certificate cert = null, tmp = null; Iterator<Certificate> itr = certs.iterator(); while (itr.hasNext()) { tmp = itr.next();/*from ww w . j a va2s . c om*/ if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) { cert = tmp; break; } } final String userName = "cmprevuser1"; if (cert == null) { createUser(userName, "CN=" + userName + ",C=SE", "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); cert = this.signSession.createCertificate(ADMIN, "cmprevuser1", "foo123", new PublicKeyWrapper(admkeys.getPublic())); } try { assertNotNull("No certificate to revoke.", cert); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genRevReq("CN=cmprevuser1,C=SE", USER_DN, CertTools.getSerialNumber(cert), cert, this.nonce, this.transid, false, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE", this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, "CN=cmprevuser1,C=SE", USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert)); assertEquals("Revocation request succeeded", RevokedCertInfo.NOT_REVOKED, revStatus); ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { PKIMessage respObject = PKIMessage.getInstance(asn1InputStream.readObject()); assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg = "CA with DN 'C=SE,CN=cmprevuser1' is unknown"; assertEquals(expectedErrMsg, errMsg); removeAuthenticationToken(adminToken, admCert, adminName); } finally { asn1InputStream.close(); } } finally { this.endEntityManagementSession.deleteUser(ADMIN, userName); } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
/** * Tests that EndEntityAuthentication module can be successfully used in client mode when the end entity's password is not stored in clear text. * /*w w w .j a v a 2 s . c o m*/ * @throws Exception */ @Test public void test21CrmfRequestClientModeEECNotClearPassword() throws Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-"); this.cmpConfiguration.setRAMode(ALIAS, false); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); final X500Name testUserDN = new X500Name("CN=cmptestuser21,C=SE"); final String testUsername = "cmptestuser21"; String fingerprint = null; String fingerprint2 = null; try { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123", new PublicKeyWrapper(keys.getPublic())); fingerprint = CertTools.getFingerprintAsString(cert); //Edit the status of the user to NEW createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(cert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(cert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); fingerprint2 = CertTools.getFingerprintAsString(cert2); } finally { try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } catch (Exception e) {// do nothing } this.internalCertStoreSession.removeCertificate(fingerprint); this.internalCertStoreSession.removeCertificate(fingerprint2); } }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid, KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateEncodingException { CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); myCertTemplate.setValidity(myOptionalValidity); if (reqSubjectDN != null) { myCertTemplate.setSubject(reqSubjectDN); }//from w w w . j a v a 2s.c om if (reqIssuerDN != null) { myCertTemplate.setIssuer(new X500Name(reqIssuerDN)); } byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try { SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (raVerifiedPopo) { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new // DERInteger(1122334455))); AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("foo123")); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(new JcaX509CertificateHolder((X509Certificate) cacert).getSubject())); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(pAlg); myPKIHeader.setSenderKID(senderKID); PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.apache.nifi.toolkit.tls.standalone.TlsToolkitStandalone.java
public void createNifiKeystoresAndTrustStores(StandaloneConfig standaloneConfig) throws GeneralSecurityException, IOException { File baseDir = standaloneConfig.getBaseDir(); if (!baseDir.exists() && !baseDir.mkdirs()) { throw new IOException(baseDir + " doesn't exist and unable to create it."); }//from w w w . j a v a2 s .c o m if (!baseDir.isDirectory()) { throw new IOException("Expected directory to output to"); } String signingAlgorithm = standaloneConfig.getSigningAlgorithm(); int days = standaloneConfig.getDays(); String keyPairAlgorithm = standaloneConfig.getKeyPairAlgorithm(); int keySize = standaloneConfig.getKeySize(); File nifiCert = new File(baseDir, NIFI_CERT + ".pem"); File nifiKey = new File(baseDir, NIFI_KEY + ".key"); X509Certificate certificate; KeyPair caKeyPair; if (logger.isInfoEnabled()) { logger.info("Running standalone certificate generation with output directory " + baseDir); } if (nifiCert.exists()) { if (!nifiKey.exists()) { throw new IOException(nifiCert + " exists already, but " + nifiKey + " does not, we need both certificate and key to continue with an existing CA."); } try (FileReader pemEncodedCertificate = new FileReader(nifiCert)) { certificate = TlsHelper.parseCertificate(pemEncodedCertificate); } try (FileReader pemEncodedKeyPair = new FileReader(nifiKey)) { caKeyPair = TlsHelper.parseKeyPair(pemEncodedKeyPair); } certificate.verify(caKeyPair.getPublic()); if (!caKeyPair.getPublic().equals(certificate.getPublicKey())) { throw new IOException("Expected " + nifiKey + " to correspond to CA certificate at " + nifiCert); } if (logger.isInfoEnabled()) { logger.info("Using existing CA certificate " + nifiCert + " and key " + nifiKey); } } else if (nifiKey.exists()) { throw new IOException(nifiKey + " exists already, but " + nifiCert + " does not, we need both certificate and key to continue with an existing CA."); } else { TlsCertificateAuthorityManager tlsCertificateAuthorityManager = new TlsCertificateAuthorityManager( standaloneConfig); KeyStore.PrivateKeyEntry privateKeyEntry = tlsCertificateAuthorityManager .getOrGenerateCertificateAuthority(); certificate = (X509Certificate) privateKeyEntry.getCertificateChain()[0]; caKeyPair = new KeyPair(certificate.getPublicKey(), privateKeyEntry.getPrivateKey()); try (PemWriter pemWriter = new PemWriter( new OutputStreamWriter(outputStreamFactory.create(nifiCert)))) { pemWriter.writeObject(new JcaMiscPEMGenerator(certificate)); } try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiKey)))) { pemWriter.writeObject(new JcaMiscPEMGenerator(caKeyPair)); } if (logger.isInfoEnabled()) { logger.info("Generated new CA certificate " + nifiCert + " and key " + nifiKey); } } NiFiPropertiesWriterFactory niFiPropertiesWriterFactory = standaloneConfig.getNiFiPropertiesWriterFactory(); boolean overwrite = standaloneConfig.isOverwrite(); List<InstanceDefinition> instanceDefinitions = standaloneConfig.getInstanceDefinitions(); if (instanceDefinitions.isEmpty() && logger.isInfoEnabled()) { logger.info("No " + TlsToolkitStandaloneCommandLine.HOSTNAMES_ARG + " specified, not generating any host certificates or configuration."); } for (InstanceDefinition instanceDefinition : instanceDefinitions) { String hostname = instanceDefinition.getHostname(); File hostDir; int hostIdentifierNumber = instanceDefinition.getInstanceIdentifier().getNumber(); if (hostIdentifierNumber == 1) { hostDir = new File(baseDir, hostname); } else { hostDir = new File(baseDir, hostname + "_" + hostIdentifierNumber); } TlsClientConfig tlsClientConfig = new TlsClientConfig(standaloneConfig); File keystore = new File(hostDir, "keystore." + tlsClientConfig.getKeyStoreType().toLowerCase()); File truststore = new File(hostDir, "truststore." + tlsClientConfig.getTrustStoreType().toLowerCase()); if (hostDir.exists()) { if (!hostDir.isDirectory()) { throw new IOException(hostDir + " exists but is not a directory."); } else if (overwrite) { if (logger.isInfoEnabled()) { logger.info("Overwriting any existing ssl configuration in " + hostDir); } keystore.delete(); if (keystore.exists()) { throw new IOException("Keystore " + keystore + " already exists and couldn't be deleted."); } truststore.delete(); if (truststore.exists()) { throw new IOException( "Truststore " + truststore + " already exists and couldn't be deleted."); } } else { throw new IOException(hostDir + " exists and overwrite is not set."); } } else if (!hostDir.mkdirs()) { throw new IOException("Unable to make directory: " + hostDir.getAbsolutePath()); } else if (logger.isInfoEnabled()) { logger.info("Writing new ssl configuration to " + hostDir); } tlsClientConfig.setKeyStore(keystore.getAbsolutePath()); tlsClientConfig.setKeyStorePassword(instanceDefinition.getKeyStorePassword()); tlsClientConfig.setKeyPassword(instanceDefinition.getKeyPassword()); tlsClientConfig.setTrustStore(truststore.getAbsolutePath()); tlsClientConfig.setTrustStorePassword(instanceDefinition.getTrustStorePassword()); TlsClientManager tlsClientManager = new TlsClientManager(tlsClientConfig); KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); Extensions sanDnsExtensions = StringUtils.isBlank(tlsClientConfig.getDomainAlternativeNames()) ? null : TlsHelper.createDomainAlternativeNamesExtensions(tlsClientConfig.getDomainAlternativeNames()); tlsClientManager.addPrivateKeyToKeyStore(keyPair, NIFI_KEY, CertificateUtils.generateIssuedCertificate(tlsClientConfig.calcDefaultDn(hostname), keyPair.getPublic(), sanDnsExtensions, certificate, caKeyPair, signingAlgorithm, days), certificate); tlsClientManager.setCertificateEntry(NIFI_CERT, certificate); tlsClientManager.addClientConfigurationWriter( new NifiPropertiesTlsClientConfigWriter(niFiPropertiesWriterFactory, new File(hostDir, "nifi.properties"), hostname, instanceDefinition.getNumber())); tlsClientManager.write(outputStreamFactory); if (logger.isInfoEnabled()) { logger.info("Successfully generated TLS configuration for " + hostname + " " + hostIdentifierNumber + " in " + hostDir); } } List<String> clientDns = standaloneConfig.getClientDns(); if (standaloneConfig.getClientDns().isEmpty() && logger.isInfoEnabled()) { logger.info("No " + TlsToolkitStandaloneCommandLine.CLIENT_CERT_DN_ARG + " specified, not generating any client certificates."); } List<String> clientPasswords = standaloneConfig.getClientPasswords(); for (int i = 0; i < clientDns.size(); i++) { String reorderedDn = CertificateUtils.reorderDn(clientDns.get(i)); String clientDnFile = getClientDnFile(reorderedDn); File clientCertFile = new File(baseDir, clientDnFile + ".p12"); if (clientCertFile.exists()) { if (overwrite) { if (logger.isInfoEnabled()) { logger.info("Overwriting existing client cert " + clientCertFile); } } else { throw new IOException(clientCertFile + " exists and overwrite is not set."); } } else if (logger.isInfoEnabled()) { logger.info("Generating new client certificate " + clientCertFile); } KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); X509Certificate clientCert = CertificateUtils.generateIssuedCertificate(reorderedDn, keyPair.getPublic(), null, certificate, caKeyPair, signingAlgorithm, days); KeyStore keyStore = KeyStoreUtils.getKeyStore(KeystoreType.PKCS12.toString()); keyStore.load(null, null); keyStore.setKeyEntry(NIFI_KEY, keyPair.getPrivate(), null, new Certificate[] { clientCert, certificate }); String password = TlsHelper.writeKeyStore(keyStore, outputStreamFactory, clientCertFile, clientPasswords.get(i), standaloneConfig.isClientPasswordsGenerated()); try (FileWriter fileWriter = new FileWriter(new File(baseDir, clientDnFile + ".password"))) { fileWriter.write(password); } if (logger.isInfoEnabled()) { logger.info("Successfully generated client certificate " + clientCertFile); } } if (logger.isInfoEnabled()) { logger.info("tls-toolkit standalone completed successfully"); } }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void generatePkcs10Request() throws Exception { // Change token to P12 UserMatch usermatch = new UserMatch(); usermatch.setMatchwith(UserMatch.MATCH_WITH_USERNAME); usermatch.setMatchtype(UserMatch.MATCH_TYPE_EQUALS); usermatch.setMatchvalue(CA1_WSTESTUSER1); List<UserDataVOWS> userdatas = ejbcaraws.findUser(usermatch); assertTrue(userdatas != null);//w w w. ja v a2 s. c o m assertTrue(userdatas.size() == 1); userdatas.get(0).setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); userdatas.get(0).setStatus(UserDataVOWS.STATUS_NEW); userdatas.get(0).setPassword(PASSWORD); userdatas.get(0).setClearPwd(true); ejbcaraws.editUser(userdatas.get(0)); KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(), keys.getPrivate(), null); CertificateResponse certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); assertTrue(certenv.getResponseType().equals(CertificateHelper.RESPONSETYPE_CERTIFICATE)); X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertTrue(cert.getSubjectDN().toString().equals(getDN(CA1_WSTESTUSER1))); ejbcaraws.editUser(userdatas.get(0)); certenv = ejbcaraws.pkcs10Request(CA1_WSTESTUSER1, PASSWORD, new String(Base64.encode(pkcs10.getEncoded())), null, CertificateHelper.RESPONSETYPE_PKCS7); assertTrue(certenv.getResponseType().equals(CertificateHelper.RESPONSETYPE_PKCS7)); CMSSignedData cmsSignedData = new CMSSignedData(CertificateHelper.getPKCS7(certenv.getData())); assertTrue(cmsSignedData != null); Store certStore = cmsSignedData.getCertificates(); assertTrue(certStore.getMatches(null).size() == 1); }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
/** * Sends a KeyUpdateRequest for a certificate that belongs to an end entity whose status is not NEW and the configurations is * NOT to allow changing the end entity status automatically. A CMP error message is expected and no certificate renewal. * // w w w . j a v a2 s . c o m * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal) * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'false' and tests that the resetting of configuration has worked. * - Pre-configuration: Sets cmp.allowupdatewithsamekey 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 * - Sends the request using HTTP and receives a response. * - Examines the response: * - Checks that the response is not empty or null * - Checks that the protection algorithm is sha1WithRSAEncryption * - Checks 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 * - Parses the response and checks that the parsing did not result in a 'null' * - Checks that the CMP response message tag number is '23', indicating a CMP error message * - Checks that the CMP response message contains the expected error details text * * @throws Exception */ @Test public void test02AutomaticUpdateNotAllowed() throws Exception { if (log.isTraceEnabled()) { log.trace(">test02AutomaticUpdateNotAllowed"); } this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, false); this.cmpConfiguration.setKurAllowSameKey(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; try { certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123", new PublicKeyWrapper(keys.getPublic())); } catch (ObjectNotFoundException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CADoesntExistsException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (EjbcaException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (AuthorizationDeniedException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } catch (CesecoreException e) { throw new CertificateCreationException("Error encountered when creating certificate", e); } 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(this.nonce)); 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 receive 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 = "Got request with status GENERATED (40), NEW, FAILED or INPROCESS required: " + this.username + "."; assertEquals(expectedErrMsg, errMsg); if (log.isTraceEnabled()) { log.trace("<test02AutomaticUpdateNotAllowed"); } }
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
protected void genTokenCertificates(boolean onlyOnce) throws Exception { GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID); boolean originalProfileSetting = gc.getEnableEndEntityProfileLimitations(); gc.setEnableEndEntityProfileLimitations(false); globalConfigurationSession.saveConfiguration(intAdmin, gc); if (certificateProfileSession.getCertificateProfileId(WSTESTPROFILE) != 0) { certificateProfileSession.removeCertificateProfile(intAdmin, WSTESTPROFILE); }// www. java 2s . com { final CertificateProfile profile = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); profile.setAllowValidityOverride(true); certificateProfileSession.addCertificateProfile(intAdmin, WSTESTPROFILE, profile); } // first a simple test UserDataVOWS tokenUser1 = new UserDataVOWS(); tokenUser1.setUsername("WSTESTTOKENUSER1"); tokenUser1.setPassword(PASSWORD); tokenUser1.setClearPwd(true); tokenUser1.setSubjectDN("CN=WSTESTTOKENUSER1"); tokenUser1.setCaName(getAdminCAName()); tokenUser1.setEmail(null); tokenUser1.setSubjectAltName(null); tokenUser1.setStatus(UserDataVOWS.STATUS_NEW); tokenUser1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); tokenUser1.setEndEntityProfileName("EMPTY"); tokenUser1.setCertificateProfileName("ENDUSER"); KeyPair basickeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA", CertTools.stringToBcX500Name("CN=NOUSED"), basickeys.getPublic(), new DERSet(), basickeys.getPrivate(), null); ArrayList<TokenCertificateRequestWS> requests = new ArrayList<TokenCertificateRequestWS>(); TokenCertificateRequestWS tokenCertReqWS = new TokenCertificateRequestWS(); tokenCertReqWS.setCAName(getAdminCAName()); tokenCertReqWS.setCertificateProfileName(WSTESTPROFILE); tokenCertReqWS.setValidityIdDays("1"); tokenCertReqWS.setPkcs10Data(basicpkcs10.getEncoded()); tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST); requests.add(tokenCertReqWS); tokenCertReqWS = new TokenCertificateRequestWS(); tokenCertReqWS.setCAName(getAdminCAName()); tokenCertReqWS.setCertificateProfileName("ENDUSER"); tokenCertReqWS.setKeyalg("RSA"); tokenCertReqWS.setKeyspec("1024"); tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST); requests.add(tokenCertReqWS); HardTokenDataWS hardTokenDataWS = setupHardTokenDataWS("12345678"); List<TokenCertificateResponseWS> responses = ejbcaraws.genTokenCertificates(tokenUser1, requests, hardTokenDataWS, true, false); assertTrue(responses.size() == 2); Iterator<TokenCertificateResponseWS> iter = responses.iterator(); TokenCertificateResponseWS next = iter.next(); assertTrue(next.getType() == HardTokenConstants.RESPONSETYPE_CERTIFICATE_RESPONSE); Certificate cert = next.getCertificate(); X509Certificate realcert = (X509Certificate) CertificateHelper.getCertificate(cert.getCertificateData()); assertNotNull(realcert); assertTrue(realcert.getNotAfter().toString(), realcert.getNotAfter().before(new Date(System.currentTimeMillis() + 2 * 24 * 3600 * 1000))); next = iter.next(); assertTrue(next.getType() == HardTokenConstants.RESPONSETYPE_KEYSTORE_RESPONSE); KeyStore keyStore = next.getKeyStore(); java.security.KeyStore realKeyStore = KeyStoreHelper.getKeyStore(keyStore.getKeystoreData(), HardTokenConstants.TOKENTYPE_PKCS12, PASSWORD); assertTrue(realKeyStore.containsAlias("WSTESTTOKENUSER1")); assertTrue(((X509Certificate) realKeyStore.getCertificate("WSTESTTOKENUSER1")).getNotAfter() .after(new Date(System.currentTimeMillis() + 48 * 24 * 3600 * 1000))); if (!onlyOnce) { try { responses = ejbcaraws.genTokenCertificates(tokenUser1, requests, hardTokenDataWS, false, false); assertTrue(false); } catch (HardTokenExistsException_Exception e) { } } certificateProfileSession.removeCertificateProfile(intAdmin, WSTESTPROFILE); gc.setEnableEndEntityProfileLimitations(originalProfileSetting); globalConfigurationSession.saveConfiguration(intAdmin, gc); }