Example usage for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier.

Prototype

ASN1ObjectIdentifier subjectKeyIdentifier

To view the source code for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier.

Click Source Link

Document

Subject Key Identifier

Usage

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;/*  w w  w  .j  a v a2  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

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));
    }/*from   www.  j a v  a  2  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.certificate.certextensions.standard.SubjectKeyIdentifier.java

License:Open Source License

@Override
public void init(final CertificateProfile certProf) {
    super.setOID(Extension.subjectKeyIdentifier.getId());
    super.setCriticalFlag(certProf.getSubjectKeyIdentifierCritical());
}

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  w  w.j  a v  a2s  .  c  om
    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 . ja va2 s . co 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.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 w w.jav  a  2 s.  c  om
    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;
}

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  ww.  j a  v a  2 s  . c om*/
    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.demoiselle.signer.core.extension.BasicCertificate.java

License:Open Source License

/**
 * //from w w  w .  j  a  v  a  2 s .com
 *
 * @return The subject key identifier of a certificate 
 * @throws IOException exception
 */
public String getSubjectKeyIdentifier() throws IOException {
    // TODO - Precisa validar este metodo com a RFC
    try {
        DEROctetString oct = (DEROctetString) getExtensionValue(Extension.subjectKeyIdentifier.getId());
        if (oct == null) {
            return null;
        }

        return toString(oct.getOctets());
    } catch (Exception error) {
        logger.info(error.getMessage());
        return null;
    }

}

From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java

License:Open Source License

protected void addSubjectAlternativeNames(X509v3CertificateBuilder certificateBuilder, KeyPair keyPair,
        @Nullable String applicationUri, List<String> dnsNames, List<String> ipAddresses)
        throws CertIOException, NoSuchAlgorithmException {

    List<GeneralName> generalNames = new ArrayList<>();

    if (applicationUri != null) {
        generalNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri));
    }//from w  w w  .  j ava 2s .  c  om

    dnsNames.stream().distinct().map(s -> new GeneralName(GeneralName.dNSName, s)).forEach(generalNames::add);

    ipAddresses.stream().distinct().map(s -> new GeneralName(GeneralName.iPAddress, s))
            .forEach(generalNames::add);

    certificateBuilder.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames.toArray(new GeneralName[] {})));

    // Subject Key Identifier
    certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
            new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
}

From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java

License:Open Source License

private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey,
        PublicKey pubKey, String sigAlg, boolean isCA)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, OperatorCreationException, CertificateException, IOException {
    int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
    // Create self signed certificate
    Date firstDate = new Date();
    // Set starting date to tomorrow
    firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000));
    Date lastDate = new Date();
    // Set Expiry in two days
    lastDate.setTime(lastDate.getTime() + ((2 * 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.  ja  va  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) {
            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) {
            publicKey = pubKey;
        } catch (NullPointerException e) {
            publicKey = pubKey;
        }
    } else {
        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);

    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
            (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn),
            new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn),
            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) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }
    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            ASN1InputStream spkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream apkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) spkiAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) apkiAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                spkiAsn1InputStream.close();
                apkiAsn1InputStream.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);
    }
    final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}