Search in sources :

Example 61 with BasicConstraints

use of org.bouncycastle.asn1.x509.BasicConstraints in project keycloak by keycloak.

the class CertificateUtils method generateV3Certificate.

/**
 * Generates version 3 {@link java.security.cert.X509Certificate}.
 *
 * @param keyPair the key pair
 * @param caPrivateKey the CA private key
 * @param caCert the CA certificate
 * @param subject the subject name
 *
 * @return the x509 certificate
 *
 * @throws Exception the exception
 */
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert, String subject) throws Exception {
    try {
        X500Name subjectDN = new X500Name("CN=" + subject);
        // Serial Number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));
        // Validity
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);
        // SubjectPublicKeyInfo
        SubjectPublicKeyInfo subjPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo);
        DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
        // Subject Key Identifier
        certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));
        // Authority Key Identifier
        certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));
        // Key Usage
        certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
        // Extended Key Usage
        KeyPurposeId[] EKU = new KeyPurposeId[2];
        EKU[0] = KeyPurposeId.id_kp_emailProtection;
        EKU[1] = KeyPurposeId.id_kp_serverAuth;
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));
        // Basic Constraints
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
        // Content Signer
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey);
        // Certificate
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v3Certificate.", e);
    }
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) BigInteger(java.math.BigInteger) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 62 with BasicConstraints

use of org.bouncycastle.asn1.x509.BasicConstraints in project Spark by igniterealtime.

the class SparkTrustManager method checkBasicConstraints.

/**
 * Checks the validity of the BasicConstraints extension of each certificate in the chain.
 *
 * Each certificate is assumed to have a BasicConstraints extension, with the exception of the leaf (end-entity)
 * certificate, which _can_ have a certificate.
 *
 * All non-leaf certificates must have the cA field set to 'true'.
 *
 * The pathLen is valid: it defines the maximum amount of intermediate certificates between the CA and the leaf
 * certificate. The leaf certificate itself is not included in the count (eg: a value of 'one' would allow for a
 * chain length of three: the leaf, one intermediate, and the root (where the value of 'one' is defined).
 *
 * This method assumes that the provided chain is in order, where the first chain is the end-entity / leaf certificate.
 *
 * The trust anchor / root CA should not be part of the certPath chain.
 *
 * @param chain The certificate chain, possibly incomplete.
 * @param trustAnchor the root CA certificate.
 * @throws CertificateException When the BasicConstraint verification fails.
 */
private void checkBasicConstraints(CertPath chain, X509Certificate trustAnchor) throws CertificateException {
    // Intentionally skipping over the first certificate, which is the end-entity certificate.
    for (int i = 1; i < chain.getCertificates().size(); i++) {
        final X509Certificate cert = (X509Certificate) chain.getCertificates().get(i);
        // The amount of certificates between the current certificate and the end-entity certificate cannot
        // exceed the value of pathLenConstraint (if the CA flag is not set, -1 will be returned)
        final int pathLenConstraint = cert.getBasicConstraints();
        final int certsSeparatingThisCertFromEndEntity = i - 1;
        if (certsSeparatingThisCertFromEndEntity > pathLenConstraint) {
            throw new CertificateException("Certificate number " + i + " in the chain failed the BasicConstraints check: " + (pathLenConstraint == -1 ? "CA flag not set" : "pathLenConstraint to small (was: " + pathLenConstraint + " needed:" + certsSeparatingThisCertFromEndEntity + ")"));
        }
    }
    // Explicitly check the trustAnchor (as it should not be in the chain)
    final int pathLenConstraint = trustAnchor.getBasicConstraints();
    final int certsSeparatingThisCertFromEndEntity = chain.getCertificates().size() - 1;
    if (certsSeparatingThisCertFromEndEntity > pathLenConstraint) {
        throw new CertificateException("Trust anchor of the chain failed the BasicConstraints check: " + (pathLenConstraint == -1 ? "CA flag not set" : "pathLenConstraint to small (was: " + pathLenConstraint + " needed:" + certsSeparatingThisCertFromEndEntity + ")"));
    }
}
Also used : DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 63 with BasicConstraints

use of org.bouncycastle.asn1.x509.BasicConstraints in project keystore-explorer by kaikramer.

the class DBasicConstraints method okPressed.

private void okPressed() {
    boolean ca = jcbSubjectIsCa.isSelected();
    int pathLengthConstraint = -1;
    String pathLengthConstraintStr = jtfPathLengthConstraint.getText().trim();
    if (pathLengthConstraintStr.length() > 0) {
        try {
            pathLengthConstraint = Integer.parseInt(pathLengthConstraintStr);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, res.getString("DBasicConstraints.InvalidLengthValue.message"), getTitle(), JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (pathLengthConstraint < 0) {
            JOptionPane.showMessageDialog(this, res.getString("DBasicConstraints.InvalidLengthValue.message"), getTitle(), JOptionPane.WARNING_MESSAGE);
            return;
        }
    }
    BasicConstraints basicConstraints;
    if (pathLengthConstraint != -1) {
        // pathLengthConstraint set automatically means ca=true
        basicConstraints = new BasicConstraints(pathLengthConstraint);
    } else {
        basicConstraints = new BasicConstraints(ca);
    }
    try {
        value = basicConstraints.getEncoded(ASN1Encoding.DER);
    } catch (IOException e) {
        DError.displayError(this, e);
        return;
    }
    closeDialog();
}
Also used : IOException(java.io.IOException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 64 with BasicConstraints

use of org.bouncycastle.asn1.x509.BasicConstraints in project keystore-explorer by kaikramer.

the class DBasicConstraints method prepopulateWithValue.

private void prepopulateWithValue(byte[] value) throws IOException {
    BasicConstraints basicConstraints = BasicConstraints.getInstance(value);
    jcbSubjectIsCa.setSelected(basicConstraints.isCA());
    if (basicConstraints.getPathLenConstraint() != null) {
        jtfPathLengthConstraint.setText("" + basicConstraints.getPathLenConstraint().intValue());
        jtfPathLengthConstraint.setCaretPosition(0);
    }
}
Also used : BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 65 with BasicConstraints

use of org.bouncycastle.asn1.x509.BasicConstraints in project keystore-explorer by kaikramer.

the class X509Ext method getBasicConstraintsStringValue.

private static String getBasicConstraintsStringValue(byte[] value) throws IOException {
    // @formatter:off
    /*
		 * BasicConstraints ::= ASN1Sequence { cA ASN1Boolean DEFAULT FALSE,
		 * pathLenConstraint ASN1Integer (0..MAX) OPTIONAL }
		 */
    // @formatter:on
    /*
         * Getting the DEFAULT returns a false ASN1Boolean when no value present
         * which saves the bother of a null check
         */
    StringBuilder sb = new StringBuilder();
    BasicConstraints basicConstraints = BasicConstraints.getInstance(value);
    boolean ca = basicConstraints.isCA();
    BigInteger pathLenConstraint = basicConstraints.getPathLenConstraint();
    if (ca) {
        sb.append(res.getString("SubjectIsCa"));
        sb.append(NEWLINE);
    } else {
        sb.append(res.getString("SubjectIsNotCa"));
        sb.append(NEWLINE);
    }
    if (pathLenConstraint != null) {
        sb.append(MessageFormat.format(res.getString("PathLengthConstraint"), pathLenConstraint.intValue()));
        sb.append(NEWLINE);
    } else {
        sb.append(res.getString("NoPathLengthConstraint"));
        sb.append(NEWLINE);
    }
    return sb.toString();
}
Also used : BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Aggregations

BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)114 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)68 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)66 X500Name (org.bouncycastle.asn1.x500.X500Name)65 ContentSigner (org.bouncycastle.operator.ContentSigner)63 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)60 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)59 BigInteger (java.math.BigInteger)57 X509Certificate (java.security.cert.X509Certificate)51 Date (java.util.Date)49 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)38 KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)36 GeneralName (org.bouncycastle.asn1.x509.GeneralName)30 IOException (java.io.IOException)29 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)28 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)22 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)21 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)21 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)19 KeyPair (java.security.KeyPair)17