List of usage examples for org.bouncycastle.asn1.x509 Extension authorityKeyIdentifier
ASN1ObjectIdentifier authorityKeyIdentifier
To view the source code for org.bouncycastle.asn1.x509 Extension authorityKeyIdentifier.
Click Source Link
From source file:org.apache.nifi.registry.security.util.CertificateUtils.java
License:Apache License
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate *//* w ww . j a va2 s . co m*/ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth })); // (3) subjectAlternativeName if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
From source file:org.apache.poi.poifs.crypt.PkiTestUtils.java
License:Apache License
static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore, Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage) throws IOException, OperatorCreationException, CertificateException { String signatureAlgorithm = "SHA1withRSA"; X500Name issuerName;/*from w w w. j ava2 s . c o m*/ if (issuerCertificate != null) { issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer(); } else { issuerName = new X500Name(subjectDn); } RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey; RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent()); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec); DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build() .get(CertificateID.HASH_SHA1); X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName, new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn), subjectPublicKeyInfo); X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc); SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo); AuthorityKeyIdentifier autKeyId = (issuerCertificate != null) ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded())) : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo); certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId); certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId); if (caFlag) { BasicConstraints bc; if (-1 == pathLength) { bc = new BasicConstraints(true); } else { bc = new BasicConstraints(pathLength); } certificateGenerator.addExtension(Extension.basicConstraints, false, bc); } if (null != crlUri) { int uri = GeneralName.uniformResourceIdentifier; DERIA5String crlUriDer = new DERIA5String(crlUri); GeneralName gn = new GeneralName(uri, crlUriDer); DERSequence gnDer = new DERSequence(gn); GeneralNames gns = GeneralNames.getInstance(gnDer); DistributionPointName dpn = new DistributionPointName(0, gns); DistributionPoint distp = new DistributionPoint(dpn, null, null); DERSequence distpDer = new DERSequence(distp); certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer); } if (null != ocspUri) { int uri = GeneralName.uniformResourceIdentifier; GeneralName ocspName = new GeneralName(uri, ocspUri); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } if (null != keyUsage) { certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage); } JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm); signerBuilder.setProvider("BC"); X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey)); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ // CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); // certificate = (X509Certificate) certificateFactory // .generateCertificate(new ByteArrayInputStream(certificate // .getEncoded())); return new JcaX509CertificateConverter().getCertificate(certHolder); }
From source file:org.apache.zookeeper.server.quorum.QuorumSSLTest.java
License:Apache License
private void buildCRL(X509Certificate x509Certificate, String crlPath) throws Exception { X509v2CRLBuilder builder = new JcaX509v2CRLBuilder(x509Certificate.getIssuerX500Principal(), certStartTime); builder.addCRLEntry(x509Certificate.getSerialNumber(), certStartTime, CRLReason.cACompromise); builder.setNextUpdate(certEndTime);//from w w w. ja va 2 s . c o m builder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(rootCertificate)); builder.addExtension(Extension.cRLNumber, false, new CRLNumber(new BigInteger("1000"))); X509CRLHolder cRLHolder = builder.build(contentSigner); PemWriter pemWriter = new PemWriter(new FileWriter(crlPath)); pemWriter.writeObject(new MiscPEMGenerator(cRLHolder)); pemWriter.flush(); pemWriter.close(); }
From source file:org.apache.zookeeper.server.quorum.QuorumSSLTest.java
License:Apache License
public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey, String hostname, String ipAddress, String crlPath, Integer ocspPort) throws Exception { X509CertificateHolder holder = new JcaX509CertificateHolder(caCert); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey); List<GeneralName> generalNames = new ArrayList<>(); if (hostname != null) { generalNames.add(new GeneralName(GeneralName.dNSName, hostname)); }//ww w . j a va2 s.co m if (ipAddress != null) { generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress)); } SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory .createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic().getEncoded())); X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils(); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()), certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic()) .addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder)) .addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); if (!generalNames.isEmpty()) { certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {}))); } if (crlPath != null) { DistributionPointName distPointOne = new DistributionPointName( new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath))); certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(distPointOne, null, null) })); } if (ocspPort != null) { certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort))); } return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer)); }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * Generate a CRL or a deltaCRL/* w w w. j av a 2 s.c o m*/ * * @param certs * list of revoked certificates * @param crlnumber * CRLNumber for this CRL * @param isDeltaCRL * true if we should generate a DeltaCRL * @param basecrlnumber * caseCRLNumber for a delta CRL, use 0 for full CRLs * @param certProfile * certificate profile for CRL Distribution point in the CRL, or null * @return CRL * @throws CryptoTokenOfflineException * @throws IllegalCryptoTokenException * @throws IOException * @throws SignatureException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CRLException * @throws NoSuchAlgorithmException */ private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL, int basecrlnumber) throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException { final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm(); if (log.isDebugEnabled()) { log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", " + basecrlnumber); } // Make DNs final X509Certificate cacert = (X509Certificate) getCACertificate(); final X500Name issuer; if (cacert == null) { // This is an initial root CA, since no CA-certificate exists // (I don't think we can ever get here!!!) final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder()); } else { issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()); } final Date thisUpdate = new Date(); final Date nextUpdate = new Date(); nextUpdate.setTime(nextUpdate.getTime() + crlPeriod); final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate); crlgen.setNextUpdate(nextUpdate); if (certs != null) { if (log.isDebugEnabled()) { log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final Iterator<RevokedCertInfo> it = certs.iterator(); while (it.hasNext()) { final RevokedCertInfo certinfo = (RevokedCertInfo) it.next(); crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(), certinfo.getReason()); } if (log.isDebugEnabled()) { log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } } // Authority key identifier if (getUseAuthorityKeyIdentifier() == true) { byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null); if (caSkid != null) { // Use subject key id from CA certificate AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } else { // Generate from SHA1 of public key ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)) .getEncoded())); try { SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) asn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } finally { asn1InputStream.close(); } } } // Authority Information Access final ASN1EncodableVector accessList = new ASN1EncodableVector(); if (getAuthorityInformationAccess() != null) { for (String url : getAuthorityInformationAccess()) { if (StringUtils.isNotEmpty(url)) { GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation)); } } } if (accessList.size() > 0) { AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess .getInstance(new DERSequence(accessList)); // "This CRL extension MUST NOT be marked critical." according to rfc4325 crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } // CRLNumber extension if (getUseCRLNumber() == true) { CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber)); crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum); } if (isDeltaCRL) { // DeltaCRLIndicator extension CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber)); crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum); } // CRL Distribution point URI and Freshest CRL DP if (getUseCrlDistributionPointOnCrl()) { String crldistpoint = getDefaultCRLDistPoint(); List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint); if (distpoints.size() > 0) { IssuingDistributionPoint idp = new IssuingDistributionPoint( distpoints.get(0).getDistributionPoint(), false, false, null, false, false); // According to the RFC, IDP must be a critical extension. // Nonetheless, at the moment, Mozilla is not able to correctly // handle the IDP extension and discards the CRL if it is critical. crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(), idp); } if (!isDeltaCRL) { String crlFreshestDP = getCADefinedFreshestCRL(); List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP); if (freshestDistPoints.size() > 0) { CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints .toArray(new DistributionPoint[freshestDistPoints.size()])); // According to the RFC, the Freshest CRL extension on a // CRL must not be marked as critical. Therefore it is // hardcoded as not critical and is independent of // getCrlDistributionPointOnCrlCritical(). crlgen.addExtension(Extension.freshestCRL, false, ext); } } } final X509CRLHolder crl; if (log.isDebugEnabled()) { log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN); try { final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg) .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480); crl = crlgen.build(signer); } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } if (log.isDebugEnabled()) { log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } // Verify using the CA certificate before returning // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL // because something is wrong... final PublicKey verifyKey; if (cacert != null) { verifyKey = cacert.getPublicKey(); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA certificate."); } } else { verifyKey = cryptoToken.getPublicKey(alias); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA token."); } } try { final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey); if (!crl.isSignatureValid(verifier)) { throw new SignatureException("Error verifying CRL to be returned."); } } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } catch (CertException e) { throw new SignatureException(e.getMessage(), e); } if (log.isDebugEnabled()) { log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } return crl; }
From source file:org.cesecore.certificates.certificate.certextensions.standard.AuthorityKeyIdentifier.java
License:Open Source License
@Override public void init(final CertificateProfile certProf) { super.setOID(Extension.authorityKeyIdentifier.getId()); super.setCriticalFlag(certProf.getAuthorityKeyIdentifierCritical()); }
From source file:org.cesecore.certificates.certificateprofile.CertificateProfileTest.java
License:Open Source License
@Test public void test06CertificateExtensions() throws Exception { CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE); // Check standard values for the certificate profile List<String> l = profile.getUsedStandardCertificateExtensions(); assertEquals(6, l.size());/*from w ww. j a v a 2 s . co m*/ assertTrue(l.contains(Extension.keyUsage.getId())); assertTrue(l.contains(Extension.basicConstraints.getId())); assertTrue(l.contains(Extension.subjectKeyIdentifier.getId())); assertTrue(l.contains(Extension.authorityKeyIdentifier.getId())); assertTrue(l.contains(Extension.subjectAlternativeName.getId())); assertTrue(l.contains(Extension.issuerAlternativeName.getId())); CertificateProfile eprofile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // Check standard values for the certificate profile l = eprofile.getUsedStandardCertificateExtensions(); assertEquals(7, l.size()); assertTrue(l.contains(Extension.keyUsage.getId())); assertTrue(l.contains(Extension.basicConstraints.getId())); assertTrue(l.contains(Extension.subjectKeyIdentifier.getId())); assertTrue(l.contains(Extension.authorityKeyIdentifier.getId())); assertTrue(l.contains(Extension.subjectAlternativeName.getId())); assertTrue(l.contains(Extension.issuerAlternativeName.getId())); assertTrue(l.contains(Extension.extendedKeyUsage.getId())); profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE); profile.setUseAuthorityInformationAccess(true); profile.setUseCertificatePolicies(true); profile.setUseCRLDistributionPoint(true); profile.setUseFreshestCRL(true); profile.setUseMicrosoftTemplate(true); profile.setUseOcspNoCheck(true); profile.setUseQCStatement(true); profile.setUseExtendedKeyUsage(true); profile.setUseSubjectDirAttributes(true); l = profile.getUsedStandardCertificateExtensions(); assertEquals(15, l.size()); assertTrue(l.contains(Extension.keyUsage.getId())); assertTrue(l.contains(Extension.basicConstraints.getId())); assertTrue(l.contains(Extension.subjectKeyIdentifier.getId())); assertTrue(l.contains(Extension.authorityKeyIdentifier.getId())); assertTrue(l.contains(Extension.subjectAlternativeName.getId())); assertTrue(l.contains(Extension.issuerAlternativeName.getId())); assertTrue(l.contains(Extension.extendedKeyUsage.getId())); assertTrue(l.contains(Extension.authorityInfoAccess.getId())); assertTrue(l.contains(Extension.certificatePolicies.getId())); assertTrue(l.contains(Extension.cRLDistributionPoints.getId())); assertTrue(l.contains(Extension.freshestCRL.getId())); assertTrue(l.contains(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())); assertTrue(l.contains(Extension.qCStatements.getId())); assertTrue(l.contains(Extension.subjectDirectoryAttributes.getId())); assertTrue(l.contains(CertTools.OID_MSTEMPLATE)); }
From source file:org.cesecore.certificates.crl.CrlCreateSessionTest.java
License:Open Source License
/** * Tests issuing a CRL from a CA with a SKID that is not generated with SHA1. * The CRL is checked to contain the correct AKID value. *///w w w. j av a2s. com @Test public void testNonSHA1KeyId() throws Exception { final String subcaname = "CrlCSTestSub"; final String subcadn = "CN=" + subcaname; try { // Create an external root ca certificate final KeyPair rootcakp = KeyTools.genKeys("1024", "RSA"); final String rootcadn = "CN=CrlCSTestRoot"; final X509Certificate rootcacert = CertTools.genSelfCert(rootcadn, 3650, null, rootcakp.getPrivate(), rootcakp.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, "BC", false); // Create sub ca final int cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(authenticationToken, subcaname, "1024"); final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId, AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA); X509CAInfo subcainfo = new X509CAInfo(subcadn, subcaname, CAConstants.CA_ACTIVE, CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA, 365, CAInfo.SIGNEDBYEXTERNALCA, null, catoken); X509CA subca = new X509CA(subcainfo); subca.setCAToken(catoken); caSession.addCA(authenticationToken, subca); // Issue sub CA certificate with a non-standard SKID PublicKey subcapubkey = cryptoTokenMgmtSession.getPublicKey(authenticationToken, cryptoTokenId, catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)).getPublicKey(); Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + 365 * 24 * 60 * 60 * 1000); final SubjectPublicKeyInfo subcaspki = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(subcapubkey.getEncoded())); final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(rootcadn, false), new BigInteger(64, new Random(System.nanoTime())), firstDate, lastDate, CertTools.stringToBcX500Name(subcadn, false), subcaspki); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(CertTools.getAuthorityKeyId(rootcacert)); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(TEST_AKID); // Non-standard SKID. It should match the AKID in the CRL certbuilder.addExtension(Extension.authorityKeyIdentifier, true, aki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); BasicConstraints bc = new BasicConstraints(true); certbuilder.addExtension(Extension.basicConstraints, true, bc); X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign); certbuilder.addExtension(Extension.keyUsage, true, ku); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(rootcakp.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate subcacert = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded(), "BC"); // Replace sub CA certificate with a sub CA cert containing the test AKID subcainfo = (X509CAInfo) caSession.getCAInfo(authenticationToken, subcaname); List<Certificate> certificatechain = new ArrayList<Certificate>(); certificatechain.add(subcacert); certificatechain.add(rootcacert); subcainfo.setCertificateChain(certificatechain); subcainfo.setExpireTime(CertTools.getNotAfter(subcacert)); caSession.editCA(authenticationToken, subcainfo); subca = (X509CA) caTestSessionRemote.getCA(authenticationToken, subcaname); assertArrayEquals("Wrong SKID in test CA.", TEST_AKID, CertTools.getSubjectKeyId(subca.getCACertificate())); // Create a base CRL and check the AKID int baseCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("For a new CA, the next crl number should be 1.", 1, baseCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), -1, baseCrlNumber); final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); checkCrlAkid(subca, crl); // Create a delta CRL and check the AKID int deltaCrlNumber = crlStoreSession.getLastCRLNumber(subcadn, false) + 1; assertEquals("Next CRL number should be 2 at this point.", 2, deltaCrlNumber); crlCreateSession.generateAndStoreCRL(authenticationToken, subca, new ArrayList<RevokedCertInfo>(), baseCrlNumber, deltaCrlNumber); final byte[] deltacrl = crlStoreSession.getLastCRL(subcadn, true); // true = get delta CRL checkCrlAkid(subca, deltacrl); } finally { // Remove everything created above to clean the database final Integer cryptoTokenId = cryptoTokenMgmtSession.getIdFromName(subcaname); if (cryptoTokenId != null) { CryptoTokenTestUtils.removeCryptoToken(authenticationToken, cryptoTokenId); } try { int caid = caSession.getCAInfo(authenticationToken, subcaname).getCAId(); // Delete sub CA CRLs while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, true); // delta CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } while (true) { final byte[] crl = crlStoreSession.getLastCRL(subcadn, false); // base CRLs if (crl == null) { break; } internalCertificateStoreSession.removeCRL(authenticationToken, CertTools.getFingerprintAsString(crl)); } // Delete sub CA caSession.removeCA(authenticationToken, caid); } catch (CADoesntExistsException cade) { // NOPMD ignore } } }
From source file:org.cesecore.certificates.crl.CrlCreateSessionTest.java
License:Open Source License
private void checkCrlAkid(X509CA subca, final byte[] crl) throws Exception { assertNotNull(crl);/*from ww w . j a va2s. c o m*/ // First, check that it is signed by the correct public key final X509CRL xcrl = CertTools.getCRLfromByteArray(crl); final PublicKey pubK = subca.getCACertificate().getPublicKey(); xcrl.verify(pubK); // Check that the correct AKID is used final byte[] akidExtBytes = xcrl.getExtensionValue(Extension.authorityKeyIdentifier.getId()); ASN1InputStream octAis = new ASN1InputStream(new ByteArrayInputStream(akidExtBytes)); DEROctetString oct = (DEROctetString) (octAis.readObject()); ASN1InputStream keyidAis = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); AuthorityKeyIdentifier akid = AuthorityKeyIdentifier.getInstance((ASN1Sequence) keyidAis.readObject()); keyidAis.close(); octAis.close(); assertArrayEquals("Incorrect Authority Key Id in CRL.", TEST_AKID, akid.getKeyIdentifier()); }
From source file:org.cesecore.util.CertTools.java
License:Open Source License
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder, List<Extension> additionalExtensions) throws CertificateParsingException, IOException, OperatorCreationException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;//from w ww . j a v a 2s . c o m if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("RSA was not a known algorithm", e); } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" final String algo = ecpk.getAlgorithm(); if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { try { publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("ECGOST3410 was not a known algorithm", e); } } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { try { publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("DSTU4145 was not a known algorithm", e); } } else { try { publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("EC was not a known algorithm", e); } } } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA1PRNG was not a known algorithm", e); } random.setSeed(new Date().getTime()); random.nextBytes(serno); SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e); } X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA || keyusage != 0) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) { final ASN1EncodableVector v = new ASN1EncodableVector(); if (privateKeyNotBefore != null) { v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore))); } if (privateKeyNotAfter != null) { v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter))); } certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v)); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream sAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream aAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) sAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) aAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { sAsn1InputStream.close(); aAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } // Add any additional if (additionalExtensions != null) { for (final Extension extension : additionalExtensions) { certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue()); } } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }