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

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

Introduction

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

Prototype

ASN1ObjectIdentifier SubjectKeyIdentifier

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

Click Source Link

Document

Subject Key Identifier

Usage

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

License:Open Source License

/**
 * Certificate issued under an existing CA.
 * @param subjectDN the distinguished name of the subject.
 * @param subjectPublicKey the public key of the subject.
 * @param issuerCertificate the certificate of the issuer.
 * @param duration the validity duration of the certificate.
 * @param isCA /*  www . ja v  a  2 s .  c  o  m*/
 * @param allUsage if isCA is true, add "regular" KeyUsage flags, for dual-use cert
 * @throws CertificateEncodingException
 * @throws IOException
 */
public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey,
        X509Certificate issuerCertificate, long duration, boolean isCA, Integer chainLength, boolean allUsage)
        throws CertificateEncodingException, IOException {

    this(subjectDN, subjectPublicKey, issuerCertificate.getSubjectX500Principal(), duration, isCA, chainLength,
            allUsage);
    // Pull the existing subject identifier out of the issuer cert. 
    byte[] subjectKeyID = issuerCertificate.getExtensionValue(X509Extensions.SubjectKeyIdentifier.toString());
    if (null == subjectKeyID) {
        subjectKeyID = CryptoUtil.generateKeyID(subjectPublicKey);

    } else {
        // content of extension is wrapped in a DEROctetString
        DEROctetString content = (DEROctetString) CryptoUtil.decode(subjectKeyID);
        byte[] encapsulatedOctetString = content.getOctets();
        DEROctetString octetStringKeyID = (DEROctetString) CryptoUtil.decode(encapsulatedOctetString);
        subjectKeyID = octetStringKeyID.getOctets();
    }
    _aki = new AuthorityKeyIdentifier(subjectKeyID);
}

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

License:Open Source License

/**
 * Basic common path./*from   w  w w .  j a  va 2 s.co 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.ejbca.core.model.ca.certextensions.standard.SubjectKeyIdentifier.java

License:Open Source License

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

From source file:org.ejbca.core.model.ca.certificateprofiles.CertificateProfileTest.java

License:Open Source License

public void test09CertificateExtensions() throws Exception {
    log.trace(">test09CertificateExtensions()");

    CertificateProfile profile = new CertificateProfile();

    // Check standard values for the certificate profile
    List l = profile.getUsedStandardCertificateExtensions();
    assertEquals(l.size(), 5);/*  w w  w.  j  a v  a2  s  .c o  m*/
    assertTrue(l.contains(X509Extensions.KeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.BasicConstraints.getId()));
    assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId()));

    CertificateProfile eprofile = new EndUserCertificateProfile();

    // Check standard values for the certificate profile
    l = eprofile.getUsedStandardCertificateExtensions();
    assertEquals(l.size(), 6);
    assertTrue(l.contains(X509Extensions.KeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.BasicConstraints.getId()));
    assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId()));
    assertTrue(l.contains(X509Extensions.ExtendedKeyUsage.getId()));

    profile = new CertificateProfile();
    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(l.size(), 14);
    assertTrue(l.contains(X509Extensions.KeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.BasicConstraints.getId()));
    assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId()));
    assertTrue(l.contains(X509Extensions.ExtendedKeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityInfoAccess.getId()));
    assertTrue(l.contains(X509Extensions.CertificatePolicies.getId()));
    assertTrue(l.contains(X509Extensions.CRLDistributionPoints.getId()));
    assertTrue(l.contains(X509Extensions.FreshestCRL.getId()));
    assertTrue(l.contains(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));
    assertTrue(l.contains(X509Extensions.QCStatements.getId()));
    assertTrue(l.contains(X509Extensions.SubjectDirectoryAttributes.getId()));
    assertTrue(l.contains(CertTools.OID_MSTEMPLATE));

}

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  . j  a v  a 2 s .co 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.globus.cog.abstraction.impl.execution.coaster.AutoCA.java

License:Open Source License

private Map<DERObjectIdentifier, DEREncodable> createExtensions(PublicKey caPub, PublicKey userPub)
        throws IOException {
    Map<DERObjectIdentifier, DEREncodable> ext = new HashMap<DERObjectIdentifier, DEREncodable>();

    // not a CA//w w w  .  j  a va 2  s  .c o  m
    ext.put(X509Extensions.BasicConstraints, new BasicConstraints(false));
    // obvious
    ext.put(X509Extensions.KeyUsage, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature));
    ext.put(X509Extensions.SubjectKeyIdentifier, getSubjectKeyInfo(userPub));
    ext.put(X509Extensions.AuthorityKeyIdentifier, getAuthorityKeyIdentifier(caPub));

    return ext;
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

License:Mozilla Public License

/**
 * Handles the nitty gritty of signing a CSR
 *
 * @param rootCert The certificate of the root authority who will vouch for the entity
 * @param rootPrivKey The private key of the root authority who will vouch for the entity
 * @param csr The entitie's CSR/*  w  w  w. ja  va  2s. co m*/
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return A certificate chain as an array of X509Certificate instances or null if an
 * error occurred
 */
private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey,
        PKCS10CertificationRequest csr, String keyType) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    try {
        Date validFrom = new Date();
        validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
        Date validTo = new Date();
        validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(rootCert.getSubjectX500Principal());
        certGen.setNotBefore(validFrom);
        certGen.setNotAfter(validTo);
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setPublicKey(csr.getPublicKey("BC"));

        if (keyType.toLowerCase().equals("rsa"))
            certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
        if (keyType.toLowerCase().equals("dsa"))
            certGen.setSignatureAlgorithm("DSAWithSHA1");

        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(rootCert));
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

        X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC");
        return new X509Certificate[] { issuedCert, rootCert };
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:org.kopi.ebics.certificate.X509Generator.java

License:Open Source License

/**
 * Returns an <code>X509Certificate</code> from a given
 * <code>KeyPair</code> and limit dates validations
 * @param keypair the given key pair//  w w w .  ja v  a 2  s . co m
 * @param issuer the certificate issuer
 * @param notBefore the begin validity date
 * @param notAfter the end validity date
 * @param keyusage the certificate key usage
 * @return the X509 certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage)
        throws GeneralSecurityException, IOException {
    X509V3CertificateGenerator generator;
    BigInteger serial;
    X509Certificate certificate;
    ASN1EncodableVector vector;

    serial = BigInteger.valueOf(generateSerial());
    generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serial);
    generator.setIssuerDN(new X509Principal(issuer));
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setSubjectDN(new X509Principal(issuer));
    generator.setPublicKey(keypair.getPublic());
    generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM);
    generator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
    generator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            getSubjectKeyIdentifier(keypair.getPublic()));
    generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            getAuthorityKeyIdentifier(keypair.getPublic(), issuer, serial));
    vector = new ASN1EncodableVector();
    vector.add(KeyPurposeId.id_kp_emailProtection);

    generator.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(new DERSequence(vector)));

    switch (keyusage) {
    case X509Constants.SIGNATURE_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation));
        break;
    case X509Constants.AUTHENTICATION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
        break;
    case X509Constants.ENCRYPTION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement));
        break;
    default:
        generator.addExtension(X509Extensions.KeyUsage, false,
                new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        break;
    }

    certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom());
    certificate.checkValidity(new Date());
    certificate.verify(keypair.getPublic());

    return certificate;
}

From source file:org.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

/**
 * Generate a CA Root certificate./*  w ww  .  ja v a  2  s  .  c om*/
 */
private static X509Certificate generateRootCert(String DN, KeyPair pair) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, DN));
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, true, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(
            new GeneralNames(new GeneralName(new X509Name(true, X509Name.DefaultLookUp, DN))), BigInteger.ONE));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(pair.getPublic()));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.nonRepudiation));
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.smimeCA | NetscapeCertType.sslCA | NetscapeCertType.objectSigning));

    return certGen.generate(pair.getPrivate(), "BC");
}

From source file:org.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

/**
 * Generate a sample V3 certificate to use as an intermediate or end entity 
 * certificate depending on the <code>isEndEntity</code> argument.
 *//* w w  w . j av a2s  . co m*/
private static X509Certificate generateV3Certificate(String DN, boolean isEndEntity, PublicKey entityKey,
        PrivateKey caKey, X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, false, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifier(caCert.getEncoded(),
                    new GeneralNames(new GeneralName(
                            new X509Name(true, X509Name.DefaultLookUp, caCert.getSubjectDN().getName()))),
                    caCert.getSerialNumber()));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));

    if (isEndEntity) {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    } else {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    }
    return certGen.generate(caKey, "BC");
}