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

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

Introduction

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

Prototype

ASN1ObjectIdentifier BasicConstraints

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

Click Source Link

Document

Basic Constraints

Usage

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

License:Apache License

/**
 * Create certificate.// ww  w . j  a v a2  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.kerby.pkix.TrustAnchorGenerator.java

License:Apache License

/**
 * Create CA certificate.//from   w ww .j  ava2  s  .c om
 *
 * @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.browsermob.proxy.selenium.CertificateCreator.java

License:Open Source License

/**
 * Creates a typical Certification Authority (CA) certificate.
 * @param keyPair/*  w  ww .ja v a 2s .  c  o  m*/
 * @throws SecurityException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@SuppressWarnings("deprecation")
public static X509Certificate createTypicalMasterCert(final KeyPair keyPair)
        throws SignatureException, InvalidKeyException, SecurityException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    X509Principal issuer = new X509Principal(
            "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US");

    // Create
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(issuer);
    v3CertGen.setSubjectDN(issuer);

    //Set validity period
    v3CertGen
            .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 48 /* months */ * (1000L * 60 * 60 * 24 * 30)));

    //Set signature algorithm & public key
    v3CertGen.setPublicKey(keyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);

    // Add typical extensions for signing cert
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

    v3CertGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign));

    DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector();

    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown));

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages));

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

    cert.checkValidity(new Date());

    cert.verify(keyPair.getPublic());

    return cert;
}

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

License:Open Source License

/**
 * Basic common path.//from  w  w w  . j  av  a 2  s  .  c om
 * @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.deviceconnect.android.ssl.AbstractKeyStoreManager.java

License:MIT License

private X509Certificate generateX509V3Certificate(final KeyPair keyPair, final X500Principal subject,
        final X500Principal issuer, final Date notBefore, final Date notAfter, final BigInteger serialNumber,
        final GeneralNames generalNames, final boolean isCA) throws GeneralSecurityException {
    Security.addProvider(new BouncyCastleProvider());
    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serialNumber);
    generator.setIssuerDN(issuer);/*from   w ww  .  j  av  a2 s  . c  o m*/
    generator.setSubjectDN(subject);
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setPublicKey(keyPair.getPublic());
    generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA));
    generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160));
    generator.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
    if (generalNames != null) {
        generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames);
    }
    return generator.generateX509Certificate(keyPair.getPrivate(), "BC");
}

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

License:Open Source License

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

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);//from w ww .j a  v  a  2 s  .c om
    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;// w  ww  .  ja va2 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/*from   w w w.  jav  a 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.globus.gsi.bc.test.BouncyCastleCertProcessingFactoryTest.java

License:Open Source License

public void testResctrictedWithOtherExt() throws Exception {

    GlobusCredential cred = GlobusCredential.getDefaultCredential();

    X509Extension ext = null;/*from  w  w w. j  av  a  2  s  . c  o m*/

    String oid = "1.2.3.4";
    String expectedValue = "foo";
    boolean critical = false;

    String policyOid = "1.2.3.4.5.6.7.8.9";
    String policyValue = "bar";

    X509ExtensionSet extSet = new X509ExtensionSet();
    ext = new X509Extension(oid, critical, expectedValue.getBytes());
    extSet.add(ext);

    BasicConstraints constraints = new BasicConstraints(false, 15);
    ext = new BouncyCastleX509Extension(X509Extensions.BasicConstraints.getId(), false, constraints);
    extSet.add(ext);

    ProxyPolicy policy = new ProxyPolicy(policyOid, policyValue.getBytes());
    ext = new ProxyCertInfoExtension(new ProxyCertInfo(policy));
    extSet.add(ext);

    GlobusCredential newCred = factory.createCredential(cred.getCertificateChain(), cred.getPrivateKey(), 512,
            60 * 60, GSIConstants.GSI_3_RESTRICTED_PROXY, extSet, null);

    X509Certificate newCert = newCred.getCertificateChain()[0];

    System.out.println(newCert);

    verifyExtension(newCert, oid, expectedValue, critical);

    byte[] realValue = X509Extension.getExtensionValue(newCert, ProxyCertInfo.OID.getId());
    assertTrue(realValue != null && realValue.length > 0);

    ProxyCertInfo proxyCertInfo = ProxyCertInfo.getInstance(realValue);

    assertTrue(proxyCertInfo != null);
    assertTrue(proxyCertInfo.getProxyPolicy() != null);
    assertEquals(policyOid, proxyCertInfo.getProxyPolicy().getPolicyLanguage().getId());
    assertEquals(policyValue, proxyCertInfo.getProxyPolicy().getPolicyAsString());
}