List of usage examples for org.bouncycastle.asn1.x509 Extension subjectAlternativeName
ASN1ObjectIdentifier subjectAlternativeName
To view the source code for org.bouncycastle.asn1.x509 Extension subjectAlternativeName.
Click Source Link
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys, Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions, Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, InvalidKeyException, SignatureException { ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); if (notBefore != null) { nb = new org.bouncycastle.asn1.x509.Time(notBefore); }/*from w w w .j av a 2 s . c o m*/ optionalValidityV.add(new DERTaggedObject(true, 0, nb)); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); if (notAfter != null) { na = new org.bouncycastle.asn1.x509.Time(notAfter); } optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); if (issuerDN != null) { myCertTemplate.setIssuer(new X500Name(issuerDN)); } myCertTemplate.setSubject(userDN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); dIn.close(); myCertTemplate.setPublicKey(keyInfo); // If we did not pass any extensions as parameter, we will create some of our own, standard ones Extensions exts = extensions; if (exts == null) { // SubjectAltName // Some altNames ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dOut = new ASN1OutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); if (altNames != null) { GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames); dOut.writeObject(san); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.subjectAlternativeName, false, value); } // KeyUsage int bcku = 0; bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation; KeyUsage ku = new KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku)); // Make the complete extension package exts = extgen.generate(); } myCertTemplate.setExtensions(exts); if (customCertSerno != null) { // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order // to request a custom certificate serial number (something not standard anyway) myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno)); } 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, "BC"); 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); } 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 X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName()))); 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(0, myCertReqMessages); // initialization // request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java
License:Open Source License
@Test public void test07ExtensionOverride() throws Exception { byte[] nonce = CmpMessageHelper.createSenderNonce(); byte[] transid = CmpMessageHelper.createSenderNonce(); // Create some crazy extensions to see that we get them when using // extension override. // We should not get our values when not using extension override ExtensionsGenerator extgen = new ExtensionsGenerator(); // SubjectAltName GeneralNames san = CertTools.getGeneralNamesFromAltName("dnsName=foo.bar.com"); extgen.addExtension(Extension.subjectAlternativeName, false, san); // KeyUsage/* www . jav a 2 s . co m*/ int bcku = 0; bcku = X509KeyUsage.decipherOnly; X509KeyUsage ku = new X509KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, ku); // Extended Key Usage List<KeyPurposeId> usage = new ArrayList<KeyPurposeId>(); usage.add(KeyPurposeId.id_kp_codeSigning); ExtendedKeyUsage eku = ExtendedKeyUsage.getInstance(usage); extgen.addExtension(Extension.extendedKeyUsage, false, eku); // OcspNoCheck extgen.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, DERNull.INSTANCE); // Netscape cert type extgen.addExtension(new ASN1ObjectIdentifier("2.16.840.1.113730.1.1"), false, new NetscapeCertType(NetscapeCertType.objectSigningCA)); // My completely own extgen.addExtension(new ASN1ObjectIdentifier("1.1.1.1.1"), false, new DERIA5String("PrimeKey")); // Make the complete extension package Extensions exts = extgen.generate(); // First test without extension override PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts, null, null, null, null, null); PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); 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 = sendCmpTcp(ba, 5); checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId); String altNames = CertTools.getSubjectAlternativeName(cert); assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1); // Check key usage that it is nonRepudiation for KeyId2 boolean[] kubits = cert.getKeyUsage(); assertFalse(kubits[0]); assertTrue(kubits[1]); assertFalse(kubits[2]); assertFalse(kubits[3]); assertFalse(kubits[4]); assertFalse(kubits[5]); assertFalse(kubits[6]); assertFalse(kubits[7]); assertFalse(kubits[8]); // Our own ext should not be here assertNull(cert.getExtensionValue("1.1.1.1.1")); assertNull(cert.getExtensionValue("2.16.840.1.113730.1.1")); assertNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())); // Skip confirmation message, we have tested that several times already // // Do the same with keyId4, that has full extension override one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts, null, null, null, null, null); req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId4", 567); ir = (CertReqMessages) req.getBody().getContent(); reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); assertNotNull(req); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(req); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpTcp(ba, 5); checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId); altNames = CertTools.getSubjectAlternativeName(cert); assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1); // Check key usage that it is decipherOnly for KeyId4 kubits = cert.getKeyUsage(); assertFalse(kubits[0]); assertFalse(kubits[1]); assertFalse(kubits[2]); assertFalse(kubits[3]); assertFalse(kubits[4]); assertFalse(kubits[5]); assertFalse(kubits[6]); assertFalse(kubits[7]); assertTrue(kubits[8]); // Our own ext should not be here assertNotNull(cert.getExtensionValue("1.1.1.1.1")); assertNotNull(cert.getExtensionValue("2.16.840.1.113730.1.1")); assertNotNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())); List<String> l = cert.getExtendedKeyUsage(); assertEquals(1, l.size()); String s = l.get(0); assertEquals(KeyPurposeId.id_kp_codeSigning.getId(), s); // Skip confirmation message, we have tested that several times already }
From source file:org.ejbca.core.protocol.cmp.CrmfRARequestTest.java
License:Open Source License
/** * Send a CMP request with SubjectAltName containing OIDs that are not defined by Ejbca. * Expected to pass and a certificate containing the unsupported OIDs is returned. * //from w w w . ja v a 2 s .co m * @throws Exception */ @Test public void test04UsingOtherNameInSubjectAltName() throws Exception { ASN1EncodableVector vec = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DERUTF8String("boo@bar"))); GeneralName gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v))); vec.add(gn); v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier("2.5.5.6")); v.add(new DERTaggedObject(true, 0, new DERIA5String("2.16.528.1.1007.99.8-1-993000027-N-99300011-00.000-00000000"))); gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v))); vec.add(gn); GeneralNames san = GeneralNames.getInstance(new DERSequence(vec)); ExtensionsGenerator gen = new ExtensionsGenerator(); gen.addExtension(Extension.subjectAlternativeName, false, san); Extensions exts = gen.generate(); final X500Name userDN = new X500Name("CN=TestAltNameUser"); final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); final int reqId; String fingerprint = null; try { final PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, exts, null, null, null, null, null); final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567); CertReqMessages ir = (CertReqMessages) req.getBody().getContent(); reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); Assert.assertNotNull(req); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId); fingerprint = CertTools.getFingerprintAsString(cert); } finally { try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "TestAltNameUser", RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); } catch (NotFoundException e) { /*Do nothing*/} try { this.internalCertStoreSession.removeCertificate(fingerprint); } catch (Exception e) { /*Do nothing*/} } }
From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java
License:Open Source License
@Override public String getRequestAltNames() { String ret = null;//from w w w .j a v a 2 s.c om final CertTemplate templ = getReq().getCertReq().getCertTemplate(); final Extensions exts = templ.getExtensions(); if (exts != null) { final Extension ext = exts.getExtension(Extension.subjectAlternativeName); if (ext != null) { ret = CertTools.getAltNameStringFromExtension(ext); } } if (log.isDebugEnabled()) { log.debug("Request altName is: " + ret); } return ret; }
From source file:org.ejbca.ra.EnrollMakeNewRequestBean.java
License:Open Source License
public void uploadCsr() { //If PROVIDED BY USER key generation is selected, try fill Subject DN fields from CSR (Overwrite the fields set by previous CSR upload if any) if (getSelectedKeyPairGenerationEnum() != null && KeyPairGeneration.PROVIDED_BY_USER.equals(getSelectedKeyPairGenerationEnum()) && algorithmFromCsr != null) { final PKCS10CertificationRequest pkcs10CertificateRequest = CertTools .getCertificateRequestFromPem(getCertificateRequest()); if (pkcs10CertificateRequest.getSubject() != null) { populateRequestFields(false, pkcs10CertificateRequest.getSubject().toString(), getSubjectDn().getFieldInstances()); getSubjectDn().update();//from w ww .j a v a 2s.co m } final Extension sanExtension = CertTools.getExtension(pkcs10CertificateRequest, Extension.subjectAlternativeName.getId()); if (sanExtension != null) { populateRequestFields(true, CertTools.getAltNameStringFromExtension(sanExtension), getSubjectAlternativeName().getFieldInstances()); getSubjectAlternativeName().update(); } // Don't make the effort to populate Subject Directory Attribute fields. Too little real world use for that. } }
From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java
License:Open Source License
@Override public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception { final boolean verbose = parameters.containsKey(VERBOSE_KEY); final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY)); final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY)); String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY); String endentityPassword = ""; if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) { endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY) ? parameters.get(AUTHENTICATION_PARAM_KEY) : "foo123"; }//w w w . jav a 2 s . com String altNames = parameters.get(ALTNAME_KEY); String serno = parameters.get(SERNO_KEY); BigInteger customCertSerno = null; if (serno != null) { customCertSerno = new BigInteger(serno, 16); } boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY); if (verbose) { log.info("Creating CRMF request with: SubjectDN=" + userDN.toString()); log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString()); log.info("Creating CRMF request with: AuthenticationModule=" + authmodule); log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword); log.info("Creating CRMF request with: SubjectAltName=" + altNames); log.info("Creating CRMF request with: CustomCertSerno=" + (customCertSerno == null ? "" : customCertSerno.toString(16))); log.info("Creating CRMF request with: IncludePopo=" + includePopo); } final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce(); final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce(); // We should be able to back date the start time when allow validity // override is enabled in the certificate profile Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_WEEK, -1); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds // in validity Date notBefore = cal.getTime(); cal.add(Calendar.DAY_OF_WEEK, 3); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore); // in validity Date notAfter = cal.getTime(); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter); ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); if (issuerDN != null) { myCertTemplate.setIssuer(issuerDN); } myCertTemplate.setSubject(userDN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); dIn.close(); myCertTemplate.setPublicKey(keyInfo); // Create standard extensions ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dOut = new ASN1OutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); if (altNames != null) { GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames); dOut.writeObject(san); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.subjectAlternativeName, false, value); } // KeyUsage int bcku = 0; bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation; KeyUsage ku = new KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku)); // Make the complete extension package Extensions exts = extgen.generate(); myCertTemplate.setExtensions(exts); if (customCertSerno != null) { // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order // to request a custom certificate serial number (something not standard anyway) myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno)); } 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 (includePopo) { 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, "BC"); 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); } else { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String(endentityPassword)); 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(issuerDN)); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(null); myPKIHeader.setSenderKID(new byte[0]); PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization // request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
/** * Generates a signed certificate//w w w . ja v a2 s . c om * * @param principal the principal of the certificate; commonly referred to as the * distinguished name (DN) * @param subjectAltNames the subject alternative names that should be added to the * certificate as an X509v3 extension. May be {@code null} * @param keyPair the key pair that will be associated with the certificate * @param caCert the CA certificate. If {@code null}, this results in a self signed * certificate * @param caPrivKey the CA private key. If {@code null}, this results in a self signed * certificate * @param isCa whether or not the generated certificate is a CA * @param days no of days certificate will be valid from now * @param signatureAlgorithm algorithm used for signing certificate. If {@code null} or * empty, then use default algorithm {@link CertGenUtils#getDefaultSignatureAlgorithm(PrivateKey)} * @return a signed {@link X509Certificate} */ private static X509Certificate generateSignedCertificate(X500Principal principal, GeneralNames subjectAltNames, KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivKey, boolean isCa, int days, String signatureAlgorithm) throws NoSuchAlgorithmException, CertificateException, CertIOException, OperatorCreationException { Objects.requireNonNull(keyPair, "Key-Pair must not be null"); final DateTime notBefore = new DateTime(DateTimeZone.UTC); if (days < 1) { throw new IllegalArgumentException("the certificate must be valid for at least one day"); } final DateTime notAfter = notBefore.plusDays(days); final BigInteger serial = CertGenUtils.getSerial(); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); X500Name subject = X500Name.getInstance(principal.getEncoded()); final X500Name issuer; final AuthorityKeyIdentifier authorityKeyIdentifier; if (caCert != null) { if (caCert.getBasicConstraints() < 0) { throw new IllegalArgumentException("ca certificate is not a CA!"); } issuer = X500Name.getInstance(caCert.getIssuerX500Principal().getEncoded()); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()); } else { issuer = subject; authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()); } JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, new Time(notBefore.toDate(), Locale.ROOT), new Time(notAfter.toDate(), Locale.ROOT), subject, keyPair.getPublic()); builder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(keyPair.getPublic())); builder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); if (subjectAltNames != null) { builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } builder.addExtension(Extension.basicConstraints, isCa, new BasicConstraints(isCa)); PrivateKey signingKey = caPrivKey != null ? caPrivKey : keyPair.getPrivate(); ContentSigner signer = new JcaContentSignerBuilder( (Strings.isNullOrEmpty(signatureAlgorithm)) ? getDefaultSignatureAlgorithm(signingKey) : signatureAlgorithm).setProvider(CertGenUtils.BC_PROV).build(signingKey); X509CertificateHolder certificateHolder = builder.build(signer); return new JcaX509CertificateConverter().getCertificate(certificateHolder); }
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
/** * Generates a certificate signing request * * @param keyPair the key pair that will be associated by the certificate generated from the certificate signing request * @param principal the principal of the certificate; commonly referred to as the distinguished name (DN) * @param sanList the subject alternative names that should be added to the certificate as an X509v3 extension. May be * {@code null}//from w ww . j a va2 s. c om * @return a certificate signing request */ static PKCS10CertificationRequest generateCSR(KeyPair keyPair, X500Principal principal, GeneralNames sanList) throws IOException, OperatorCreationException { Objects.requireNonNull(keyPair, "Key-Pair must not be null"); Objects.requireNonNull(keyPair.getPublic(), "Public-Key must not be null"); Objects.requireNonNull(principal, "Principal must not be null"); JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(principal, keyPair.getPublic()); if (sanList != null) { ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, false, sanList); builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()); } return builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(CertGenUtils.BC_PROV) .build(keyPair.getPrivate())); }
From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateToolTests.java
License:Open Source License
public void testGeneratingCsr() throws Exception { Path tempDir = initTempDir(); Path outputFile = tempDir.resolve("out.zip"); Path instanceFile = writeInstancesTo(tempDir.resolve("instances.yml")); Collection<CertificateInformation> certInfos = CertificateGenerateTool.parseFile(instanceFile); assertEquals(4, certInfos.size());/*from www . java2 s . c o m*/ assertFalse(Files.exists(outputFile)); CertificateGenerateTool.generateAndWriteCsrs(outputFile, certInfos, randomFrom(1024, 2048)); assertTrue(Files.exists(outputFile)); Set<PosixFilePermission> perms = Files.getPosixFilePermissions(outputFile); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_READ)); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_WRITE)); assertEquals(perms.toString(), 2, perms.size()); FileSystem fileSystem = FileSystems.newFileSystem(new URI("jar:" + outputFile.toUri()), Collections.emptyMap()); Path zipRoot = fileSystem.getPath("/"); assertFalse(Files.exists(zipRoot.resolve("ca"))); for (CertificateInformation certInfo : certInfos) { String filename = certInfo.name.filename; assertTrue(Files.exists(zipRoot.resolve(filename))); final Path csr = zipRoot.resolve(filename + "/" + filename + ".csr"); assertTrue(Files.exists(csr)); assertTrue(Files.exists(zipRoot.resolve(filename + "/" + filename + ".key"))); PKCS10CertificationRequest request = readCertificateRequest(csr); assertEquals(certInfo.name.x500Principal.getName(), request.getSubject().toString()); Attribute[] extensionsReq = request.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (certInfo.ipAddresses.size() > 0 || certInfo.dnsNames.size() > 0) { assertEquals(1, extensionsReq.length); Extensions extensions = Extensions.getInstance(extensionsReq[0].getAttributeValues()[0]); GeneralNames subjAltNames = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); assertSubjAltNames(subjAltNames, certInfo); } else { assertEquals(0, extensionsReq.length); } } }
From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateToolTests.java
License:Open Source License
public void testGeneratingSignedCertificates() throws Exception { Path tempDir = initTempDir(); Path outputFile = tempDir.resolve("out.zip"); Path instanceFile = writeInstancesTo(tempDir.resolve("instances.yml")); Collection<CertificateInformation> certInfos = CertificateGenerateTool.parseFile(instanceFile); assertEquals(4, certInfos.size());//from w ww . j av a 2 s . co m final int keysize = randomFrom(1024, 2048); final int days = randomIntBetween(1, 1024); KeyPair keyPair = CertGenUtils.generateKeyPair(keysize); X509Certificate caCert = CertGenUtils.generateCACertificate(new X500Principal("CN=test ca"), keyPair, days); final boolean generatedCa = randomBoolean(); final char[] keyPassword = randomBoolean() ? SecuritySettingsSourceField.TEST_PASSWORD.toCharArray() : null; final char[] pkcs12Password = randomBoolean() ? randomAlphaOfLengthBetween(1, 12).toCharArray() : null; assertFalse(Files.exists(outputFile)); CAInfo caInfo = new CAInfo(caCert, keyPair.getPrivate(), generatedCa, keyPassword); CertificateGenerateTool.generateAndWriteSignedCertificates(outputFile, certInfos, caInfo, keysize, days, pkcs12Password); assertTrue(Files.exists(outputFile)); Set<PosixFilePermission> perms = Files.getPosixFilePermissions(outputFile); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_READ)); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_WRITE)); assertEquals(perms.toString(), 2, perms.size()); FileSystem fileSystem = FileSystems.newFileSystem(new URI("jar:" + outputFile.toUri()), Collections.emptyMap()); Path zipRoot = fileSystem.getPath("/"); if (generatedCa) { assertTrue(Files.exists(zipRoot.resolve("ca"))); assertTrue(Files.exists(zipRoot.resolve("ca").resolve("ca.crt"))); assertTrue(Files.exists(zipRoot.resolve("ca").resolve("ca.key"))); // check the CA cert try (InputStream input = Files.newInputStream(zipRoot.resolve("ca").resolve("ca.crt"))) { X509Certificate parsedCaCert = readX509Certificate(input); assertThat(parsedCaCert.getSubjectX500Principal().getName(), containsString("test ca")); assertEquals(caCert, parsedCaCert); long daysBetween = ChronoUnit.DAYS.between(caCert.getNotBefore().toInstant(), caCert.getNotAfter().toInstant()); assertEquals(days, (int) daysBetween); } // check the CA key if (keyPassword != null) { try (Reader reader = Files.newBufferedReader(zipRoot.resolve("ca").resolve("ca.key"))) { PEMParser pemParser = new PEMParser(reader); Object parsed = pemParser.readObject(); assertThat(parsed, instanceOf(PEMEncryptedKeyPair.class)); char[] zeroChars = new char[keyPassword.length]; Arrays.fill(zeroChars, (char) 0); assertArrayEquals(zeroChars, keyPassword); } } PrivateKey privateKey = PemUtils.readPrivateKey(zipRoot.resolve("ca").resolve("ca.key"), () -> keyPassword != null ? SecuritySettingsSourceField.TEST_PASSWORD.toCharArray() : null); assertEquals(caInfo.privateKey, privateKey); } else { assertFalse(Files.exists(zipRoot.resolve("ca"))); } for (CertificateInformation certInfo : certInfos) { String filename = certInfo.name.filename; assertTrue(Files.exists(zipRoot.resolve(filename))); final Path cert = zipRoot.resolve(filename + "/" + filename + ".crt"); assertTrue(Files.exists(cert)); assertTrue(Files.exists(zipRoot.resolve(filename + "/" + filename + ".key"))); final Path p12 = zipRoot.resolve(filename + "/" + filename + ".p12"); try (InputStream input = Files.newInputStream(cert)) { X509Certificate certificate = readX509Certificate(input); assertEquals(certInfo.name.x500Principal.toString(), certificate.getSubjectX500Principal().getName()); final int sanCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size() + certInfo.commonNames.size(); if (sanCount == 0) { assertNull(certificate.getSubjectAlternativeNames()); } else { X509CertificateHolder x509CertHolder = new X509CertificateHolder(certificate.getEncoded()); GeneralNames subjAltNames = GeneralNames.fromExtensions(x509CertHolder.getExtensions(), Extension.subjectAlternativeName); assertSubjAltNames(subjAltNames, certInfo); } if (pkcs12Password != null) { assertThat(p12, pathExists(p12)); try (InputStream in = Files.newInputStream(p12)) { final KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(in, pkcs12Password); final Certificate p12Certificate = ks.getCertificate(certInfo.name.originalName); assertThat("Certificate " + certInfo.name, p12Certificate, notNullValue()); assertThat(p12Certificate, equalTo(certificate)); final Key key = ks.getKey(certInfo.name.originalName, pkcs12Password); assertThat(key, notNullValue()); } } else { assertThat(p12, not(pathExists(p12))); } } } }