List of usage examples for org.bouncycastle.asn1.x509 SubjectKeyIdentifier SubjectKeyIdentifier
protected SubjectKeyIdentifier(ASN1OctetString keyid)
From source file:org.apache.kerby.pkix.EndEntityGenerator.java
License:Apache License
/** * Generate certificate.//from ww w . j a va 2 s . c o m * * @param issuerCert * @param issuerPrivateKey * @param publicKey * @param dn * @param validityDays * @param friendlyName * @return The certificate. * @throws InvalidKeyException * @throws SecurityException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws DataLengthException * @throws CertificateException */ public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey, PublicKey publicKey, String dn, int validityDays, String friendlyName) throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CertificateException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Set certificate attributes. certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert)); certGen.setSubjectDN(new X509Principal(dn)); certGen.setNotBefore(new Date()); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); certGen.setNotAfter(expiry.getTime()); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); // MAY set BasicConstraints=false or not at all. certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)); ASN1EncodableVector keyPurposeVector = new ASN1EncodableVector(); keyPurposeVector.add(KeyPurposeId.id_kp_smartcardlogon); //keyPurposeVector.add( KeyPurposeId.id_kp_serverAuth ); DERSequence keyPurposeOids = new DERSequence(keyPurposeVector); // If critical, will throw unsupported EKU. certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, keyPurposeOids); ASN1EncodableVector pkinitSanVector = new ASN1EncodableVector(); pkinitSanVector.add(ID_PKINIT_SAN); pkinitSanVector.add(new DERTaggedObject(0, new DERSequence())); DERSequence pkinitSan = new DERSequence(pkinitSanVector); String dnsName = "localhost"; GeneralName name1 = new GeneralName(GeneralName.otherName, pkinitSan); GeneralName name2 = new GeneralName(GeneralName.dNSName, dnsName); GeneralNamesBuilder genNamesBuilder = new GeneralNamesBuilder(); genNamesBuilder.addName(name1); genNamesBuilder.addName(name2); GeneralNames sanGeneralNames = genNamesBuilder.build(); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, sanGeneralNames); /* * The KDC MAY require the presence of an Extended Key Usage (EKU) KeyPurposeId * [RFC3280] id-pkinit-KPClientAuth in the extensions field of the client's * X.509 certificate. */ /* * The digitalSignature key usage bit [RFC3280] MUST be asserted when the * intended purpose of the client's X.509 certificate is restricted with * the id-pkinit-KPClientAuth EKU. */ /* * KDCs implementing this requirement SHOULD also accept the EKU KeyPurposeId * id-ms-kp-sc-logon (1.3.6.1.4.1.311.20.2.2) as meeting the requirement, as * there are a large number of X.509 client certificates deployed for use * with PKINIT that have this EKU. */ // KDC /* * In addition, unless the client can otherwise verify that the public key * used to verify the KDC's signature is bound to the KDC of the target realm, * the KDC's X.509 certificate MUST contain a Subject Alternative Name extension * [RFC3280] carrying an AnotherName whose type-id is id-pkinit-san (as defined * in Section 3.2.2) and whose value is a KRB5PrincipalName that matches the * name of the TGS of the target realm (as defined in Section 7.3 of [RFC4120]). */ /* * Unless the client knows by some other means that the KDC certificate is * intended for a Kerberos KDC, the client MUST require that the KDC certificate * contains the EKU KeyPurposeId [RFC3280] id-pkinit-KPKdc. */ /* * The digitalSignature key usage bit [RFC3280] MUST be asserted when the * intended purpose of the KDC's X.509 certificate is restricted with the * id-pkinit-KPKdc EKU. */ /* * If the KDC certificate contains the Kerberos TGS name encoded as an id-pkinit-san * SAN, this certificate is certified by the issuing CA as a KDC certificate, * therefore the id-pkinit-KPKdc EKU is not required. */ /* * KDC certificates issued by Windows 2000 Enterprise CAs contain a dNSName * SAN with the DNS name of the host running the KDC, and the id-kp-serverAuth * EKU [RFC3280]. */ /* * KDC certificates issued by Windows 2003 Enterprise CAs contain a dNSName * SAN with the DNS name of the host running the KDC, the id-kp-serverAuth * EKU, and the id-ms-kp-sc-logon EKU. */ /* * RFC: KDC certificates with id-pkinit-san SAN as specified in this RFC. * * MS: dNSName SAN containing the domain name of the KDC * id-pkinit-KPKdc EKU * id-kp-serverAuth EKU. */ /* * Client certificates accepted by Windows 2000 and Windows 2003 Server KDCs * must contain an id-ms-san-sc-logon-upn (1.3.6.1.4.1.311.20.2.3) SAN and * the id-ms-kp-sc-logon EKU. The id-ms-san-sc-logon-upn SAN contains a * UTF8-encoded string whose value is that of the Directory Service attribute * UserPrincipalName of the client account object, and the purpose of including * the id-ms-san-sc-logon-upn SAN in the client certificate is to validate * the client mapping (in other words, the client's public key is bound to * the account that has this UserPrincipalName value). */ X509Certificate cert = certGen.generate(issuerPrivateKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName)); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); return cert; }
From source file:org.apache.kerby.pkix.IntermediateCaGenerator.java
License:Apache License
/** * Create certificate.//from w w w . j ava 2s . co m * * @param issuerCert * @param issuerPrivateKey * @param publicKey * @param dn * @param validityDays * @param friendlyName * @return The certificate. * @throws InvalidKeyException * @throws SecurityException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws DataLengthException * @throws CertificateException */ public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey, PublicKey publicKey, String dn, int validityDays, String friendlyName) throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CertificateException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Set certificate attributes. certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert)); certGen.setSubjectDN(new X509Principal(dn)); certGen.setNotBefore(new Date()); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); certGen.setNotAfter(expiry.getTime()); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); X509Certificate cert = certGen.generate(issuerPrivateKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName)); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); return cert; }
From source file:org.apache.kerby.pkix.TrustAnchorGenerator.java
License:Apache License
/** * Create CA certificate./* w w w.j a v a 2 s . com*/ * * @param publicKey * @param privateKey * @param dn * @param validityDays * @param friendlyName * @return The certificate. * @throws InvalidKeyException * @throws SecurityException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws DataLengthException * @throws CertificateException */ public static X509Certificate generate(PublicKey publicKey, PrivateKey privateKey, String dn, int validityDays, String friendlyName) throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CertificateException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Set certificate attributes. certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); X509Principal x509Principal = new X509Principal(dn); certGen.setIssuerDN(x509Principal); certGen.setSubjectDN(x509Principal); certGen.setNotBefore(new Date()); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); certGen.setNotAfter(expiry.getTime()); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(1)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); X509Certificate cert = certGen.generate(privateKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName)); bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())))); return cert; }
From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCertificateGenerator.java
License:Open Source License
/** * Basic common path./* ww w . j a v a2 s .c o m*/ * @param subjectDN the distinguished name of the subject. * @param subjectPublicKey the public key of the subject. * @param issuerDN the distinguished name of the issuer. * @param duration the validity duration of the certificate. * @param isCA * @param allUsage if isCA is true, add "regular" KeyUsage flags, for dual-use cert */ public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey, X500Principal issuerDN, long duration, boolean isCA, Integer chainLength, boolean allUsage) { _generator.setSubjectDN(new X509Name(subjectDN)); _generator.setIssuerDN(issuerDN); _generator.setSerialNumber(new BigInteger(64, cachedRandom)); _generator.setPublicKey(subjectPublicKey); Date startTime = new Date(); Date stopTime = new Date(startTime.getTime() + duration); _generator.setNotBefore(startTime); _generator.setNotAfter(stopTime); // CA key usage final int caKeyUsage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyCertSign | KeyUsage.cRLSign; // Non-CA key usage final int nonCAKeyUsage = KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement; int ourUsage; if (isCA) { if (!allUsage) { ourUsage = caKeyUsage; } else { ourUsage = caKeyUsage | nonCAKeyUsage; } } else { ourUsage = nonCAKeyUsage; } _generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(ourUsage)); BasicConstraints bc = ((isCA == false) || (null == chainLength)) ? new BasicConstraints(isCA) : new BasicConstraints(chainLength.intValue()); _generator.addExtension(X509Extensions.BasicConstraints, true, bc); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(CryptoUtil.generateKeyID(subjectPublicKey)); _generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); }
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. *//*from w w w . j av a2s . c o m*/ @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.conscrypt.java.security.cert.CertificateFactoryTest.java
License:Apache License
@SuppressWarnings("deprecation") private static KeyHolder generateCertificate(boolean isCa, KeyHolder issuer) throws Exception { Date startDate = new Date(); GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.set(2100, 0, 1, 0, 0, 0); // Jan 1, 2100 UTC Date expiryDate = cal.getTime(); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = kpg.generateKeyPair(); BigInteger serial;/*w w w . ja v a 2 s . c o m*/ X500Principal issuerPrincipal; X500Principal subjectPrincipal; PrivateKey caKey; if (issuer != null) { serial = issuer.certificate.getSerialNumber().add(BigInteger.ONE); subjectPrincipal = new X500Principal("CN=Test Certificate Serial #" + serial.toString()); issuerPrincipal = issuer.certificate.getSubjectX500Principal(); caKey = issuer.privateKey; } else { serial = BigInteger.ONE; subjectPrincipal = new X500Principal("CN=Test CA, O=Tests, C=US"); issuerPrincipal = subjectPrincipal; caKey = keyPair.getPrivate(); } BasicConstraints basicConstraints; if (isCa) { basicConstraints = new BasicConstraints(10 - serial.intValue()); } else { basicConstraints = new BasicConstraints(false); } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); PublicKey pubKey = keyPair.getPublic(); certGen.setSerialNumber(serial); certGen.setIssuerDN(issuerPrincipal); certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(subjectPrincipal); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("SHA1withRSA"); if (issuer != null) { certGen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuer.certificate)); } else { certGen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(generatePublicKeyDigest(pubKey))); } certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(generatePublicKeyDigest(pubKey))); certGen.addExtension(Extension.basicConstraints, true, basicConstraints); X509Certificate cert = certGen.generate(caKey); KeyHolder holder = new KeyHolder(); holder.certificate = cert; holder.privateKey = keyPair.getPrivate(); return holder; }
From source file:org.ejbca.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, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { // 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))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // 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;// www.jav a 2 s . 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; } } 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" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } 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 = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); certgen.setSerialNumber(new java.math.BigInteger(serno).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(publicKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey, provider); return selfcert; }
From source file:org.ejbca.util.keystore.KeyTools.java
License:Open Source License
/** * create the subject key identifier./*w ww . j a v a2 s. c om*/ * * @param pubKey the public key * * @return SubjectKeyIdentifer asn.1 structure */ public static SubjectKeyIdentifier createSubjectKeyId(final PublicKey pubKey) { try { final ASN1Sequence keyASN1Sequence; final Object keyObject = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject(); if (keyObject instanceof ASN1Sequence) { keyASN1Sequence = (ASN1Sequence) keyObject; } else { // PublicKey key that don't encode to a ASN1Sequence. Fix this by creating a BC object instead. final PublicKey altKey = (PublicKey) KeyFactory.getInstance(pubKey.getAlgorithm(), "BC") .translateKey(pubKey); keyASN1Sequence = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(altKey.getEncoded())) .readObject(); } return new SubjectKeyIdentifier(new SubjectPublicKeyInfo(keyASN1Sequence)); } catch (Exception e) { final RuntimeException e2 = new RuntimeException("error creating key"); // NOPMD e2.initCause(e); throw e2; } }
From source file:org.globus.cog.abstraction.impl.execution.coaster.AutoCA.java
License:Open Source License
private DEREncodable getSubjectKeyInfo(PublicKey userPub) throws IOException { // convert key to bouncy castle format and get subject key identifier DERObject derKey = new ASN1InputStream(userPub.getEncoded()).readObject(); return new SubjectKeyIdentifier(new SubjectPublicKeyInfo((ASN1Sequence) derKey)); }
From source file:org.keycloak.common.util.OCSPUtils.java
License:Apache License
private static void verifyResponse(BasicOCSPResp basicOcspResponse, X509Certificate issuerCertificate, X509Certificate responderCertificate, byte[] requestNonce, Date date) throws NoSuchProviderException, NoSuchAlgorithmException, CertificateNotYetValidException, CertificateExpiredException, CertPathValidatorException { List<X509CertificateHolder> certs = new ArrayList<>(Arrays.asList(basicOcspResponse.getCerts())); X509Certificate signingCert = null; try {//from ww w .j av a2 s . com certs.add(new JcaX509CertificateHolder(issuerCertificate)); if (responderCertificate != null) { certs.add(new JcaX509CertificateHolder(responderCertificate)); } } catch (CertificateEncodingException e) { e.printStackTrace(); } if (certs.size() > 0) { X500Name responderName = basicOcspResponse.getResponderId().toASN1Primitive().getName(); byte[] responderKey = basicOcspResponse.getResponderId().toASN1Primitive().getKeyHash(); if (responderName != null) { logger.log(Level.INFO, "Responder Name: {0}", responderName.toString()); for (X509CertificateHolder certHolder : certs) { try { X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certHolder); X500Name respName = new X500Name(tempCert.getSubjectX500Principal().getName()); if (responderName.equals(respName)) { signingCert = tempCert; logger.log(Level.INFO, "Found a certificate whose principal \"{0}\" matches the responder name \"{1}\"", new Object[] { tempCert.getSubjectDN().getName(), responderName.toString() }); break; } } catch (CertificateException e) { logger.log(Level.FINE, e.getMessage()); } } } else if (responderKey != null) { SubjectKeyIdentifier responderSubjectKey = new SubjectKeyIdentifier(responderKey); logger.log(Level.INFO, "Responder Key: {0}", Arrays.toString(responderKey)); for (X509CertificateHolder certHolder : certs) { try { X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certHolder); SubjectKeyIdentifier subjectKeyIdentifier = null; if (certHolder.getExtensions() != null) { subjectKeyIdentifier = SubjectKeyIdentifier.fromExtensions(certHolder.getExtensions()); } if (subjectKeyIdentifier != null) { logger.log(Level.INFO, "Certificate: {0}\nSubject Key Id: {1}", new Object[] { tempCert.getSubjectDN().getName(), Arrays.toString(subjectKeyIdentifier.getKeyIdentifier()) }); } if (subjectKeyIdentifier != null && responderSubjectKey.equals(subjectKeyIdentifier)) { signingCert = tempCert; logger.log(Level.INFO, "Found a signer certificate \"{0}\" with the subject key extension value matching the responder key", signingCert.getSubjectDN().getName()); break; } subjectKeyIdentifier = new JcaX509ExtensionUtils() .createSubjectKeyIdentifier(tempCert.getPublicKey()); if (responderSubjectKey.equals(subjectKeyIdentifier)) { signingCert = tempCert; logger.log(Level.INFO, "Found a certificate \"{0}\" with the subject key matching the OCSP responder key", signingCert.getSubjectDN().getName()); break; } } catch (CertificateException e) { logger.log(Level.FINE, e.getMessage()); } } } } if (signingCert != null) { if (signingCert.equals(issuerCertificate)) { logger.log(Level.INFO, "OCSP response is signed by the target''s Issuing CA"); } else if (responderCertificate != null && signingCert.equals(responderCertificate)) { // https://www.ietf.org/rfc/rfc2560.txt // 2.6 OCSP Signature Authority Delegation // - The responder certificate is issued to the responder by CA logger.log(Level.INFO, "OCSP response is signed by an authorized responder certificate"); } else { // 4.2.2.2 Authorized Responders // 3. Includes a value of id-ad-ocspSigning in an ExtendedKeyUsage // extension and is issued by the CA that issued the certificate in // question." if (!signingCert.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) { logger.log(Level.INFO, "Signer certificate''s Issuer: {0}\nIssuer certificate''s Subject: {1}", new Object[] { signingCert.getIssuerX500Principal().getName(), issuerCertificate.getSubjectX500Principal().getName() }); throw new CertPathValidatorException( "Responder\'s certificate is not authorized to sign OCSP responses"); } try { List<String> purposes = signingCert.getExtendedKeyUsage(); if (purposes != null && !purposes.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { logger.log(Level.INFO, "OCSPSigning extended usage is not set"); throw new CertPathValidatorException( "Responder\'s certificate not valid for signing OCSP responses"); } } catch (CertificateParsingException e) { logger.log(Level.FINE, "Failed to get certificate''s extended key usage extension\n{0}", e.getMessage()); } if (date == null) { signingCert.checkValidity(); } else { signingCert.checkValidity(date); } try { Extension noOCSPCheck = new JcaX509CertificateHolder(signingCert) .getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck); // TODO If the extension is present, the OCSP client can trust the // responder's certificate for the lifetime of the certificate. logger.log(Level.INFO, "OCSP no-check extension is {0} present", noOCSPCheck == null ? "not" : ""); } catch (CertificateEncodingException e) { logger.log(Level.FINE, "Certificate encoding exception: {0}", e.getMessage()); } try { signingCert.verify(issuerCertificate.getPublicKey()); logger.log(Level.INFO, "OCSP response is signed by an Authorized Responder"); } catch (GeneralSecurityException ex) { signingCert = null; } } } if (signingCert == null) { throw new CertPathValidatorException("Unable to verify OCSP Response\'s signature"); } else { if (!verifySignature(basicOcspResponse, signingCert)) { throw new CertPathValidatorException("Error verifying OCSP Response\'s signature"); } else { Extension responseNonce = basicOcspResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (responseNonce != null && requestNonce != null && !Arrays.equals(requestNonce, responseNonce.getExtnValue().getOctets())) { throw new CertPathValidatorException("Nonces do not match."); } else { // See Sun's OCSP implementation. // https://www.ietf.org/rfc/rfc2560.txt, if nextUpdate is not set, // the responder is indicating that newer update is avilable all the time long current = date == null ? System.currentTimeMillis() : date.getTime(); Date stop = new Date(current + (long) TIME_SKEW); Date start = new Date(current - (long) TIME_SKEW); Iterator<SingleResp> iter = Arrays.asList(basicOcspResponse.getResponses()).iterator(); SingleResp singleRes = null; do { if (!iter.hasNext()) { return; } singleRes = iter.next(); } while (!stop.before(singleRes.getThisUpdate()) && !start.after(singleRes.getNextUpdate() != null ? singleRes.getNextUpdate() : singleRes.getThisUpdate())); throw new CertPathValidatorException( "Response is unreliable: its validity interval is out-of-date"); } } } }