Example usage for org.bouncycastle.asn1.x509 X509Extensions AuthorityKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions AuthorityKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Extensions AuthorityKeyIdentifier.

Prototype

ASN1ObjectIdentifier AuthorityKeyIdentifier

To view the source code for org.bouncycastle.asn1.x509 X509Extensions AuthorityKeyIdentifier.

Click Source Link

Document

Authority Key Identifier

Usage

From source file:org.apache.kerby.pkix.IntermediateCaGenerator.java

License:Apache License

/**
 * Create certificate.//from w w  w  . ja va2 s .com
 *
 * @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.synapse.transport.certificatevalidation.CRLVerifierTest.java

License:Apache License

/**
 * Creates a fake CRL for the fake CA. The fake certificate with the given revokedSerialNumber will be marked
 * as Revoked in the returned CRL.//  w w  w  .  j  a v a2s  .c o m
 * @param caCert the fake CA certificate.
 * @param caPrivateKey private key of the fake CA.
 * @param revokedSerialNumber the serial number of the fake peer certificate made to be marked as revoked.
 * @return the created fake CRL
 * @throws Exception
 */
public static X509CRL createCRL(X509Certificate caCert, PrivateKey caPrivateKey, BigInteger revokedSerialNumber)
        throws Exception {

    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    Date now = new Date();
    crlGen.setIssuerDN(caCert.getSubjectX500Principal());
    crlGen.setThisUpdate(now);
    crlGen.setNextUpdate(new Date(now.getTime() + TestConstants.NEXT_UPDATE_PERIOD));
    crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    crlGen.addCRLEntry(revokedSerialNumber, now, CRLReason.privilegeWithdrawn);
    crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1)));

    return crlGen.generateX509CRL(caPrivateKey, "BC");
}

From source file:org.atticfs.key.KeyUtils.java

License:Apache License

public static X509Certificate createSignedCertificate(KeyPair keyPair, PrivateKey caKey, X509Certificate caCert,
        String dn, int days) throws Exception {
    Date startDate = new Date();
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_YEAR, days);

    Date expiryDate = cal.getTime();
    BigInteger serialNumber = randomHexInteger(64);

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal subjectName = new X500Principal(dn);

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(startDate);//from w  w w. j a va2 s . co m
    certGen.setNotAfter(expiryDate);

    certGen.setSubjectDN(subjectName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    X509Certificate cert = certGen.generate(caKey, providerName); // note: private key of CA
    return cert;
}

From source file:org.browsermob.proxy.selenium.CertificateCreator.java

License:Open Source License

/**
 * This method creates an X509v3 certificate based on an an existing certificate.
 * It attempts to create as faithful a copy of the existing certificate as possible
 * by duplicating all certificate extensions.
 *
 * If you are testing an application that makes use of additional certificate
 * extensions (e.g. logotype, S/MIME capabilities) this method will preserve those
 * fields.//from   w  w  w  .j a va2s.  com
 *
 * You may optionally include a set of OIDs not to copy from the original certificate.
 * The most common reason to do this would be to remove fields that would cause inconsistency,
 * such as Authority Info Access or Issuer Alternative Name where these are not defined for
 * the MITM authority certificate.
 *
 * OIDs 2.5.29.14 : Subject Key Identifier and 2.5.29.35 : Authority Key Identifier,
 * are never copied, but generated directly based on the input keys and certificates.
 *
 * You may also optionally include maps of custom extensions which will be added to or replace
 * extensions with the same OID on the original certificate for the the MITM certificate.
 *
 * FUTURE WORK: JDK 1.5 is very strict in parsing extensions.  In particular, known extensions
 * that include URIs must parse to valid URIs (including URL encoding all non-valid URI characters)
 * or the extension will be rejected and not available to copy to the MITM certificate.  Will need
 * to directly extract these as ASN.1 fields and re-insert (hopefully BouncyCastle will handle them)
 *
 *
 * @param originalCert  The original certificate to duplicate.
 * @param newPubKey     The new public key for the MITM certificate.
 * @param caCert        The certificate of the signing authority fot the MITM certificate.
 * @param caPrivateKey  The private key of the signing authority.
 * @param extensionOidsNotToCopy  An optional list of certificate extension OIDs not to copy to the MITM certificate.
 * @param criticalCustomExtensions An optional map of critical extension OIDs to add/replace on the MITM certificate.
 * @param noncriticalCustomExtensions An optional map of non-critical extension OIDs to add/replace on the MITM certificate.
 * @return The new MITM certificate.
 * @throws CertificateParsingException
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws CertificateExpiredException
 * @throws CertificateNotYetValidException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static X509Certificate mitmDuplicateCertificate(final X509Certificate originalCert,
        final PublicKey newPubKey, final X509Certificate caCert, final PrivateKey caPrivateKey,
        Set<String> extensionOidsNotToCopy, Map<String, DEREncodable> criticalCustomExtensions,
        Map<String, DEREncodable> noncriticalCustomExtensions)
        throws CertificateParsingException, SignatureException, InvalidKeyException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {
    if (extensionOidsNotToCopy == null) {
        extensionOidsNotToCopy = new HashSet<String>();
    }
    if (noncriticalCustomExtensions == null) {
        noncriticalCustomExtensions = new HashMap<String, DEREncodable>();
    }
    if (criticalCustomExtensions == null) {
        criticalCustomExtensions = new HashMap<String, DEREncodable>();
    }

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    v3CertGen.setSubjectDN(originalCert.getSubjectX500Principal());
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // needs to be the same as the signing cert, not the copied cert
    v3CertGen.setPublicKey(newPubKey);
    v3CertGen.setNotAfter(originalCert.getNotAfter());
    v3CertGen.setNotBefore(originalCert.getNotBefore());
    v3CertGen.setIssuerDN(caCert.getSubjectX500Principal());
    v3CertGen.setSerialNumber(originalCert.getSerialNumber());

    // copy other extensions:
    Set<String> critExts = originalCert.getCriticalExtensionOIDs();

    // get extensions returns null, not an empty set!
    if (critExts != null) {
        for (String oid : critExts) {
            if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)
                    && !criticalCustomExtensions.containsKey(oid)) {
                v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), true, originalCert);
            }
        }
    }
    Set<String> nonCritExs = originalCert.getNonCriticalExtensionOIDs();

    if (nonCritExs != null) {
        for (String oid : nonCritExs) {

            if (!clientCertOidsNeverToCopy.contains(oid) && !extensionOidsNotToCopy.contains(oid)
                    && !noncriticalCustomExtensions.containsKey(oid)) {
                v3CertGen.copyAndAddExtension(new DERObjectIdentifier(oid), false, originalCert);
            }
        }
    }

    for (Map.Entry<String, DEREncodable> customExtension : criticalCustomExtensions.entrySet()) {
        v3CertGen.addExtension(customExtension.getKey(), true, customExtension.getValue());
    }

    for (Map.Entry<String, DEREncodable> customExtension : noncriticalCustomExtensions.entrySet()) {
        v3CertGen.addExtension(customExtension.getKey(), false, customExtension.getValue());
    }

    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(newPubKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert.getPublicKey()));

    X509Certificate cert = v3CertGen.generate(caPrivateKey, "BC");

    // For debugging purposes.
    //cert.checkValidity(new Date());
    //cert.verify(caCert.getPublicKey());

    return cert;
}

From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java

License:Open Source License

@Override
public X509Certificate createX509Certificate(String dn, Set<X509ExtensionWrapper> extensions,
        Set<X509ByteExtensionWrapper> byteExtensions, Date startDate, Date endDate, KeyPair clientKeyPair,
        BigInteger serialNumber, String alternateName) throws GeneralSecurityException, IOException {

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X509Certificate caCert = reader.getCACert();
    // set cert fields
    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(startDate);/*w w  w  .j a va 2 s . c o  m*/
    certGen.setNotAfter(endDate);

    X500Principal subjectPrincipal = new X500Principal(dn);
    certGen.setSubjectDN(subjectPrincipal);
    certGen.setPublicKey(clientKeyPair.getPublic());
    certGen.setSignatureAlgorithm(SIGNATURE_ALGO);

    // set key usage - required for proper x509 function
    KeyUsage keyUsage = new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);

    // add SSL extensions - required for proper x509 function
    NetscapeCertType certType = new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime);

    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType.toString(), false, certType);
    certGen.addExtension(X509Extensions.KeyUsage.toString(), false, keyUsage);

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            subjectKeyWriter.getSubjectKeyIdentifier(clientKeyPair, extensions));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

    // Add an alternate name if provided
    if (alternateName != null) {
        GeneralName name = new GeneralName(GeneralName.uniformResourceIdentifier, "CN=" + alternateName);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(name));
    }

    if (extensions != null) {
        for (X509ExtensionWrapper wrapper : extensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            String value = wrapper.getValue() == null ? "" : wrapper.getValue();
            certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DERUTF8String(value));
        }
    }

    if (byteExtensions != null) {
        for (X509ByteExtensionWrapper wrapper : byteExtensions) {
            // Bouncycastle hates null values. So, set them to blank
            // if they are null
            byte[] value = wrapper.getValue() == null ? new byte[0] : wrapper.getValue();
            certGen.addExtension(wrapper.getOid(), wrapper.isCritical(), new DEROctetString(value));
        }
    }

    // Generate the certificate
    return certGen.generate(reader.getCaKey());
}

From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java

License:Open Source License

@Override
public X509CRL createX509CRL(List<X509CRLEntryWrapper> entries, BigInteger crlNumber) {

    try {//from w w  w .  ja  v a 2  s .co m
        X509Certificate caCert = reader.getCACert();
        X509V2CRLGenerator generator = new X509V2CRLGenerator();
        generator.setIssuerDN(caCert.getIssuerX500Principal());
        generator.setThisUpdate(new Date());
        generator.setNextUpdate(Util.tomorrow());
        generator.setSignatureAlgorithm(SIGNATURE_ALGO);
        // add all the CRL entries.
        for (X509CRLEntryWrapper entry : entries) {
            generator.addCRLEntry(entry.getSerialNumber(), entry.getRevocationDate(),
                    CRLReason.privilegeWithdrawn);
        }
        log.info("Completed adding CRL numbers to the certificate.");
        generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCert));
        generator.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(crlNumber));
        return generator.generate(reader.getCaKey());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCertificateGenerator.java

License:Open Source License

/**
 * Adds an authority key identifier extension to the certificate.
 *//*from www .  ja  v a 2s  . c o m*/
protected void addAuthorityKeyIdentifierExtension() {
    if (null == _aki)
        return;
    _generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, _aki);
}

From source file:org.ccnx.ccn.impl.security.crypto.util.MinimalCertificateGenerator.java

License:Open Source License

/**
 * Open up the ability to add additional extensions that aren't 
 * EKU or SubjectAltName (which we manage).
 *//*w  w w. j  av a 2s . c o  m*/
public void addExtension(String oid, boolean critical, byte[] value) {
    if (null == oid)
        throw new IllegalArgumentException("OID cannot be null!");

    DERObjectIdentifier derOID = new DERObjectIdentifier(oid);
    if ((derOID.equals(X509Extensions.ExtendedKeyUsage))
            || (derOID.equals(X509Extensions.SubjectAlternativeName))
            || (derOID.equals(X509Extensions.AuthorityKeyIdentifier))) {
        throw new IllegalArgumentException(
                "Cannot use addExtension to set ExtendedKeyUsage or SubjectAlternativeName or AuthorityKeyIdentifier!");
    }
    _generator.addExtension(derOID, critical, value);
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/** Generate a CRL or a deltaCRL
 * /*from www. j a  v 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 CATokenOfflineException
 * @throws IllegalKeyStoreException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private CRL generateCRL(Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL,
        int basecrlnumber)
        throws CATokenOfflineException, IllegalKeyStoreException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }
    Date thisUpdate = new Date();
    Date nextUpdate = new Date();

    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    X509V2CRLGenerator crlgen = new X509V2CRLGenerator();
    crlgen.setThisUpdate(thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    crlgen.setSignatureAlgorithm(sigAlg);
    // Make DNs
    X509Certificate cacert = (X509Certificate) getCACertificate();
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        X509NameEntryConverter converter = null;
        if (getUsePrintableStringSubjectDN()) {
            converter = new PrintableStringEntryConverter();
        } else {
            converter = new X509DefaultEntryConverter();
        }

        X509Name caname = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder());
        crlgen.setIssuerDN(caname);
    } else {
        crlgen.setIssuerDN(cacert.getSubjectX500Principal());
    }
    if (certs != null) {
        Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(
                new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN).getEncoded()))
                        .readObject());
        AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
        crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), getAuthorityKeyIdentifierCritical(),
                aki);
    }
    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(X509Extensions.CRLNumber.getId(), this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(X509Extensions.DeltaCRLIndicator.getId(), 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(X509Extensions.IssuingDistributionPoint.getId(),
                    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(X509Extensions.FreshestCRL.getId(), false, ext);
            }

        }
    }

    X509CRL crl;
    crl = crlgen.generate(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN),
            getCAToken().getProvider());
    // 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...
    PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN);
    }
    crl.verify(verifyKey);

    return crl;
}

From source file:org.ejbca.core.model.ca.certextensions.standard.AuthorityKeyIdentifier.java

License:Open Source License

@Override
public void init(final CertificateProfile certProf) {
    super.setOID(X509Extensions.AuthorityKeyIdentifier.getId());
    super.setCriticalFlag(certProf.getAuthorityKeyIdentifierCritical());
}