Search in sources :

Example 1 with BasicConstraints

use of org.spongycastle.asn1.x509.BasicConstraints in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method prepareNextCertM.

protected static int prepareNextCertM(CertPath certPath, int index, int maxPathLength) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    //
    // (m)
    //
    BasicConstraints bc = null;
    try {
        bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.BASIC_CONSTRAINTS));
    } catch (Exception e) {
        throw new ExtCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, index);
    }
    if (bc != null) {
        BigInteger _pathLengthConstraint = bc.getPathLenConstraint();
        if (_pathLengthConstraint != null) {
            int _plc = _pathLengthConstraint.intValue();
            if (_plc < maxPathLength) {
                return _plc;
            }
        }
    }
    return maxPathLength;
}
Also used : ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) BigInteger(java.math.BigInteger) List(java.util.List) ArrayList(java.util.ArrayList) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint)

Example 2 with BasicConstraints

use of org.spongycastle.asn1.x509.BasicConstraints in project nhin-d by DirectProject.

the class CertGenerator method createNewCA.

private static CertCreateFields createNewCA(CertCreateFields fields, KeyPair keyPair, boolean addAltNames) throws Exception {
    StringBuilder dnBuilder = new StringBuilder();
    String altName = "";
    // create the DN
    if (fields.getAttributes().containsKey("EMAILADDRESS")) {
        dnBuilder.append("EMAILADDRESS=").append(fields.getAttributes().get("EMAILADDRESS")).append(", ");
        altName = fields.getAttributes().get("EMAILADDRESS").toString();
    }
    if (fields.getAttributes().containsKey("CN"))
        dnBuilder.append("CN=").append(fields.getAttributes().get("CN")).append(", ");
    if (fields.getAttributes().containsKey("C"))
        dnBuilder.append("C=").append(fields.getAttributes().get("C")).append(", ");
    if (fields.getAttributes().containsKey("ST"))
        dnBuilder.append("ST=").append(fields.getAttributes().get("ST")).append(", ");
    if (fields.getAttributes().containsKey("L"))
        dnBuilder.append("L=").append(fields.getAttributes().get("L")).append(", ");
    if (fields.getAttributes().containsKey("O"))
        dnBuilder.append("O=").append(fields.getAttributes().get("O")).append(", ");
    String DN = dnBuilder.toString().trim();
    if (DN.endsWith(","))
        DN = DN.substring(0, DN.length() - 1);
    X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.DAY_OF_MONTH, fields.getExpDays());
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    v1CertGen.setIssuerDN(new X509Principal(DN));
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    // issuer and subject are the same for a CA
    v1CertGen.setSubjectDN(new X509Principal(DN));
    v1CertGen.setPublicKey(keyPair.getPublic());
    v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");
    v1CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    if (addAltNames && !altName.isEmpty()) {
        int nameType = altName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        GeneralNames subjectAltName = new GeneralNames(new GeneralName(nameType, altName));
        v1CertGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
    }
    X509Certificate newCACert = v1CertGen.generate(keyPair.getPrivate(), CryptoExtensions.getJCEProviderName());
    // validate the certificate 
    newCACert.verify(keyPair.getPublic());
    // write the certificate the file system
    writeCertAndKey(newCACert, keyPair.getPrivate(), fields);
    return fields;
}
Also used : X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Principal(org.bouncycastle.jce.X509Principal) Calendar(java.util.Calendar) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate)

Example 3 with BasicConstraints

use of org.spongycastle.asn1.x509.BasicConstraints in project robovm by robovm.

the class RFC3280CertPathUtilities method prepareNextCertK.

protected static void prepareNextCertK(CertPath certPath, int index) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    //
    // (k)
    //
    BasicConstraints bc = null;
    try {
        bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.BASIC_CONSTRAINTS));
    } catch (Exception e) {
        throw new ExtCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, index);
    }
    if (bc != null) {
        if (!(bc.isCA())) {
            throw new CertPathValidatorException("Not a CA certificate");
        }
    } else {
        throw new CertPathValidatorException("Intermediate certificate lacks BasicConstraints");
    }
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) List(java.util.List) ArrayList(java.util.ArrayList) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException)

Example 4 with BasicConstraints

use of org.spongycastle.asn1.x509.BasicConstraints in project robovm by robovm.

the class RFC3280CertPathUtilities method processCRLB2.

/**
     * If the complete CRL includes an issuing distribution point (IDP) CRL
     * extension check the following:
     * <p/>
     * (i) If the distribution point name is present in the IDP CRL extension
     * and the distribution field is present in the DP, then verify that one of
     * the names in the IDP matches one of the names in the DP. If the
     * distribution point name is present in the IDP CRL extension and the
     * distribution field is omitted from the DP, then verify that one of the
     * names in the IDP matches one of the names in the cRLIssuer field of the
     * DP.
     * </p>
     * <p/>
     * (ii) If the onlyContainsUserCerts boolean is asserted in the IDP CRL
     * extension, verify that the certificate does not include the basic
     * constraints extension with the cA boolean asserted.
     * </p>
     * <p/>
     * (iii) If the onlyContainsCACerts boolean is asserted in the IDP CRL
     * extension, verify that the certificate includes the basic constraints
     * extension with the cA boolean asserted.
     * </p>
     * <p/>
     * (iv) Verify that the onlyContainsAttributeCerts boolean is not asserted.
     * </p>
     *
     * @param dp   The distribution point.
     * @param cert The certificate.
     * @param crl  The CRL.
     * @throws AnnotatedException if one of the conditions is not met or an error occurs.
     */
protected static void processCRLB2(DistributionPoint dp, Object cert, X509CRL crl) throws AnnotatedException {
    IssuingDistributionPoint idp = null;
    try {
        idp = IssuingDistributionPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(crl, RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT));
    } catch (Exception e) {
        throw new AnnotatedException("Issuing distribution point extension could not be decoded.", e);
    }
    // distribution point name is present
    if (idp != null) {
        if (idp.getDistributionPoint() != null) {
            // make list of names
            DistributionPointName dpName = IssuingDistributionPoint.getInstance(idp).getDistributionPoint();
            List names = new ArrayList();
            if (dpName.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                for (int j = 0; j < genNames.length; j++) {
                    names.add(genNames[j]);
                }
            }
            if (dpName.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) {
                ASN1EncodableVector vec = new ASN1EncodableVector();
                try {
                    Enumeration e = ASN1Sequence.getInstance(ASN1Sequence.fromByteArray(CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded())).getObjects();
                    while (e.hasMoreElements()) {
                        vec.add((ASN1Encodable) e.nextElement());
                    }
                } catch (IOException e) {
                    throw new AnnotatedException("Could not read CRL issuer.", e);
                }
                vec.add(dpName.getName());
                names.add(new GeneralName(X509Name.getInstance(new DERSequence(vec))));
            }
            boolean matches = false;
            // of the names in the DP.
            if (dp.getDistributionPoint() != null) {
                dpName = dp.getDistributionPoint();
                GeneralName[] genNames = null;
                if (dpName.getType() == DistributionPointName.FULL_NAME) {
                    genNames = GeneralNames.getInstance(dpName.getName()).getNames();
                }
                if (dpName.getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER) {
                    if (dp.getCRLIssuer() != null) {
                        genNames = dp.getCRLIssuer().getNames();
                    } else {
                        genNames = new GeneralName[1];
                        try {
                            genNames[0] = new GeneralName(new X509Name((ASN1Sequence) ASN1Sequence.fromByteArray(CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).getEncoded())));
                        } catch (IOException e) {
                            throw new AnnotatedException("Could not read certificate issuer.", e);
                        }
                    }
                    for (int j = 0; j < genNames.length; j++) {
                        Enumeration e = ASN1Sequence.getInstance(genNames[j].getName().toASN1Primitive()).getObjects();
                        ASN1EncodableVector vec = new ASN1EncodableVector();
                        while (e.hasMoreElements()) {
                            vec.add((ASN1Encodable) e.nextElement());
                        }
                        vec.add(dpName.getName());
                        genNames[j] = new GeneralName(new X509Name(new DERSequence(vec)));
                    }
                }
                if (genNames != null) {
                    for (int j = 0; j < genNames.length; j++) {
                        if (names.contains(genNames[j])) {
                            matches = true;
                            break;
                        }
                    }
                }
                if (!matches) {
                    throw new AnnotatedException("No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
                }
            } else // verify that one of the names in
            // the IDP matches one of the names in the cRLIssuer field of
            // the DP
            {
                if (dp.getCRLIssuer() == null) {
                    throw new AnnotatedException("Either the cRLIssuer or the distributionPoint field must " + "be contained in DistributionPoint.");
                }
                GeneralName[] genNames = dp.getCRLIssuer().getNames();
                for (int j = 0; j < genNames.length; j++) {
                    if (names.contains(genNames[j])) {
                        matches = true;
                        break;
                    }
                }
                if (!matches) {
                    throw new AnnotatedException("No match for certificate CRL issuing distribution point name to cRLIssuer CRL distribution point.");
                }
            }
        }
        BasicConstraints bc = null;
        try {
            bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue((X509Extension) cert, BASIC_CONSTRAINTS));
        } catch (Exception e) {
            throw new AnnotatedException("Basic constraints extension could not be decoded.", e);
        }
        if (cert instanceof X509Certificate) {
            // (b) (2) (ii)
            if (idp.onlyContainsUserCerts() && (bc != null && bc.isCA())) {
                throw new AnnotatedException("CA Cert CRL only contains user certificates.");
            }
            // (b) (2) (iii)
            if (idp.onlyContainsCACerts() && (bc == null || !bc.isCA())) {
                throw new AnnotatedException("End CRL only contains CA certificates.");
            }
        }
        // (b) (2) (iv)
        if (idp.onlyContainsAttributeCerts()) {
            throw new AnnotatedException("onlyContainsAttributeCerts boolean is asserted.");
        }
    }
}
Also used : IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) Enumeration(java.util.Enumeration) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) X509Certificate(java.security.cert.X509Certificate) DERSequence(org.bouncycastle.asn1.DERSequence) X509Name(org.bouncycastle.asn1.x509.X509Name) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 5 with BasicConstraints

use of org.spongycastle.asn1.x509.BasicConstraints in project robovm by robovm.

the class TestKeyStore method createCertificate.

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.
    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);
    BigInteger serial = BigInteger.valueOf(1);
    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha1WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha1WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }
    X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
    x509cg.setSubjectDN(subject);
    x509cg.setIssuerDN(issuer);
    x509cg.setNotBefore(start);
    x509cg.setNotAfter(end);
    x509cg.setPublicKey(publicKey);
    x509cg.setSignatureAlgorithm(signatureAlgorithm);
    x509cg.setSerialNumber(serial);
    if (keyUsage != 0) {
        x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    }
    for (int i = 0; i < extendedKeyUsages.size(); i++) {
        KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
        boolean critical = criticalExtendedKeyUsages.get(i);
        x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
    }
    for (GeneralName subjectAltName : subjectAltNames) {
        x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
    }
    if (privateKey instanceof ECPrivateKey) {
        /*
             * bouncycastle needs its own ECPrivateKey implementation
             */
        KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        privateKey = kf.generatePrivate(ks);
    }
    X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
    if (StandardNames.IS_RI) {
        /*
             * The RI can't handle the BC EC signature algorithm
             * string of "ECDSA", since it expects "...WITHEC...",
             * so convert from BC to RI X509Certificate
             * implementation via bytes.
             */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) NameConstraints(com.android.org.bouncycastle.asn1.x509.NameConstraints) KeyPurposeId(com.android.org.bouncycastle.asn1.x509.KeyPurposeId) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(com.android.org.bouncycastle.asn1.x509.KeyUsage) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) CertificateFactory(java.security.cert.CertificateFactory) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(com.android.org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) GeneralName(com.android.org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(com.android.org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)57 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)30 X509Certificate (java.security.cert.X509Certificate)29 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)28 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)26 Date (java.util.Date)25 ContentSigner (org.bouncycastle.operator.ContentSigner)25 X500Name (org.bouncycastle.asn1.x500.X500Name)24 BigInteger (java.math.BigInteger)22 KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)21 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)21 GeneralName (org.bouncycastle.asn1.x509.GeneralName)20 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)17 IOException (java.io.IOException)15 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)15 ExtendedKeyUsage (org.bouncycastle.asn1.x509.ExtendedKeyUsage)13 ArrayList (java.util.ArrayList)11 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)11 KeyPair (java.security.KeyPair)10 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)10