Search in sources :

Example 1 with GeneralName

use of org.bouncycastle.asn1.x509.GeneralName in project OpenAttestation by OpenAttestation.

the class X509Builder method dnsAlternativeName.

public X509Builder dnsAlternativeName(String dns) {
    try {
        v3();
        String alternativeName = dns;
        if (dns.startsWith("dns:")) {
            alternativeName = dns.substring(4);
        }
        DNSName dnsName = new DNSName(alternativeName);
        if (alternativeNames == null) {
            alternativeNames = new GeneralNames();
        }
        alternativeNames.add(new GeneralName(dnsName));
        SubjectAlternativeNameExtension san = new SubjectAlternativeNameExtension(alternativeNames);
        if (certificateExtensions == null) {
            certificateExtensions = new CertificateExtensions();
        }
        certificateExtensions.set(san.getExtensionId().toString(), san);
        info.set(X509CertInfo.EXTENSIONS, certificateExtensions);
    } catch (Exception e) {
        fault(e, "dnsAlternativeName(%s)", dns);
    }
    return this;
}
Also used : GeneralNames(sun.security.x509.GeneralNames) SubjectAlternativeNameExtension(sun.security.x509.SubjectAlternativeNameExtension) CertificateExtensions(sun.security.x509.CertificateExtensions) GeneralName(sun.security.x509.GeneralName) DNSName(sun.security.x509.DNSName)

Example 2 with GeneralName

use of org.bouncycastle.asn1.x509.GeneralName in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 3 with GeneralName

use of org.bouncycastle.asn1.x509.GeneralName in project XobotOS by xamarin.

the class X509CertSelector method match.

/**
     * Returns whether the specified certificate matches all the criteria
     * collected in this instance.
     *
     * @param certificate
     *            the certificate to check.
     * @return {@code true} if the certificate matches all the criteria,
     *         otherwise {@code false}.
     */
public boolean match(Certificate certificate) {
    if (!(certificate instanceof X509Certificate)) {
        return false;
    }
    X509Certificate cert = (X509Certificate) certificate;
    if ((certificateEquals != null) && !certificateEquals.equals(cert)) {
        return false;
    }
    if ((serialNumber != null) && !serialNumber.equals(cert.getSerialNumber())) {
        return false;
    }
    if ((issuer != null) && !issuer.equals(cert.getIssuerX500Principal())) {
        return false;
    }
    if ((subject != null) && !subject.equals(cert.getSubjectX500Principal())) {
        return false;
    }
    if ((subjectKeyIdentifier != null) && !Arrays.equals(subjectKeyIdentifier, // are taken from rfc 3280 (http://www.ietf.org/rfc/rfc3280.txt)
    getExtensionValue(cert, "2.5.29.14"))) {
        return false;
    }
    if ((authorityKeyIdentifier != null) && !Arrays.equals(authorityKeyIdentifier, getExtensionValue(cert, "2.5.29.35"))) {
        return false;
    }
    if (certificateValid != null) {
        try {
            cert.checkValidity(certificateValid);
        } catch (CertificateExpiredException e) {
            return false;
        } catch (CertificateNotYetValidException e) {
            return false;
        }
    }
    if (privateKeyValid != null) {
        try {
            byte[] bytes = getExtensionValue(cert, "2.5.29.16");
            if (bytes == null) {
                return false;
            }
            PrivateKeyUsagePeriod pkup = (PrivateKeyUsagePeriod) PrivateKeyUsagePeriod.ASN1.decode(bytes);
            Date notBefore = pkup.getNotBefore();
            Date notAfter = pkup.getNotAfter();
            if ((notBefore == null) && (notAfter == null)) {
                return false;
            }
            if ((notBefore != null) && notBefore.compareTo(privateKeyValid) > 0) {
                return false;
            }
            if ((notAfter != null) && notAfter.compareTo(privateKeyValid) < 0) {
                return false;
            }
        } catch (IOException e) {
            return false;
        }
    }
    if (subjectPublicKeyAlgID != null) {
        try {
            byte[] encoding = cert.getPublicKey().getEncoded();
            AlgorithmIdentifier ai = ((SubjectPublicKeyInfo) SubjectPublicKeyInfo.ASN1.decode(encoding)).getAlgorithmIdentifier();
            if (!subjectPublicKeyAlgID.equals(ai.getAlgorithm())) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    if (subjectPublicKey != null) {
        if (!Arrays.equals(subjectPublicKey, cert.getPublicKey().getEncoded())) {
            return false;
        }
    }
    if (keyUsage != null) {
        boolean[] ku = cert.getKeyUsage();
        if (ku != null) {
            int i = 0;
            int min_length = (ku.length < keyUsage.length) ? ku.length : keyUsage.length;
            for (; i < min_length; i++) {
                if (keyUsage[i] && !ku[i]) {
                    // but certificate does not.
                    return false;
                }
            }
            for (; i < keyUsage.length; i++) {
                if (keyUsage[i]) {
                    return false;
                }
            }
        }
    }
    if (extendedKeyUsage != null) {
        try {
            List keyUsage = cert.getExtendedKeyUsage();
            if (keyUsage != null) {
                if (!keyUsage.containsAll(extendedKeyUsage)) {
                    return false;
                }
            }
        } catch (CertificateParsingException e) {
            return false;
        }
    }
    if (pathLen != -1) {
        int p_len = cert.getBasicConstraints();
        if ((pathLen < 0) && (p_len >= 0)) {
            // need end-entity but got CA
            return false;
        }
        if ((pathLen > 0) && (pathLen > p_len)) {
            // allowed _pathLen is small
            return false;
        }
    }
    if (subjectAltNames != null) {
        PASSED: try {
            byte[] bytes = getExtensionValue(cert, "2.5.29.17");
            if (bytes == null) {
                return false;
            }
            List<GeneralName> sans = ((GeneralNames) GeneralNames.ASN1.decode(bytes)).getNames();
            if ((sans == null) || (sans.size() == 0)) {
                return false;
            }
            boolean[][] map = new boolean[9][];
            // initialize the check map
            for (int i = 0; i < 9; i++) {
                map[i] = (subjectAltNames[i] == null) ? EmptyArray.BOOLEAN : new boolean[subjectAltNames[i].size()];
            }
            for (GeneralName name : sans) {
                int tag = name.getTag();
                for (int i = 0; i < map[tag].length; i++) {
                    if (subjectAltNames[tag].get(i).equals(name)) {
                        if (!matchAllNames) {
                            break PASSED;
                        }
                        map[tag][i] = true;
                    }
                }
            }
            if (!matchAllNames) {
                // there was not any match
                return false;
            }
            // else check the map
            for (int tag = 0; tag < 9; tag++) {
                for (int name = 0; name < map[tag].length; name++) {
                    if (!map[tag][name]) {
                        return false;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    if (nameConstraints != null) {
        if (!nameConstraints.isAcceptable(cert)) {
            return false;
        }
    }
    if (policies != null) {
        byte[] bytes = getExtensionValue(cert, "2.5.29.32");
        if (bytes == null) {
            return false;
        }
        if (policies.size() == 0) {
            // one policy in it.
            return true;
        }
        PASSED: try {
            List<PolicyInformation> policyInformations = ((CertificatePolicies) CertificatePolicies.ASN1.decode(bytes)).getPolicyInformations();
            for (PolicyInformation policyInformation : policyInformations) {
                if (policies.contains(policyInformation.getPolicyIdentifier())) {
                    break PASSED;
                }
            }
            return false;
        } catch (IOException e) {
            // the extension is invalid
            return false;
        }
    }
    if (pathToNames != null) {
        byte[] bytes = getExtensionValue(cert, "2.5.29.30");
        if (bytes != null) {
            NameConstraints nameConstraints;
            try {
                nameConstraints = (NameConstraints) NameConstraints.ASN1.decode(bytes);
            } catch (IOException e) {
                // the extension is invalid;
                return false;
            }
            if (!nameConstraints.isAcceptable(pathToNames)) {
                return false;
            }
        }
    }
    return true;
}
Also used : NameConstraints(org.apache.harmony.security.x509.NameConstraints) PolicyInformation(org.apache.harmony.security.x509.PolicyInformation) IOException(java.io.IOException) SubjectPublicKeyInfo(org.apache.harmony.security.x509.SubjectPublicKeyInfo) Date(java.util.Date) AlgorithmIdentifier(org.apache.harmony.security.x509.AlgorithmIdentifier) ArrayList(java.util.ArrayList) List(java.util.List) GeneralName(org.apache.harmony.security.x509.GeneralName) PrivateKeyUsagePeriod(org.apache.harmony.security.x509.PrivateKeyUsagePeriod)

Example 4 with GeneralName

use of org.bouncycastle.asn1.x509.GeneralName in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCRLB1.

/**
     * If the DP includes cRLIssuer, then verify that the issuer field in the
     * complete CRL matches cRLIssuer in the DP and that the complete CRL
     * contains an issuing distribution point extension with the indirectCRL
     * boolean asserted. Otherwise, verify that the CRL issuer matches the
     * certificate issuer.
     *
     * @param dp   The distribution point.
     * @param cert The certificate ot attribute certificate.
     * @param crl  The CRL for <code>cert</code>.
     * @throws AnnotatedException if one of the above conditions does not apply or an error
     *                            occurs.
     */
protected static void processCRLB1(DistributionPoint dp, Object cert, X509CRL crl) throws AnnotatedException {
    DERObject idp = CertPathValidatorUtilities.getExtensionValue(crl, ISSUING_DISTRIBUTION_POINT);
    boolean isIndirect = false;
    if (idp != null) {
        if (IssuingDistributionPoint.getInstance(idp).isIndirectCRL()) {
            isIndirect = true;
        }
    }
    byte[] issuerBytes = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
    boolean matchIssuer = false;
    if (dp.getCRLIssuer() != null) {
        GeneralName[] genNames = dp.getCRLIssuer().getNames();
        for (int j = 0; j < genNames.length; j++) {
            if (genNames[j].getTagNo() == GeneralName.directoryName) {
                try {
                    if (Arrays.areEqual(genNames[j].getName().getDERObject().getEncoded(), issuerBytes)) {
                        matchIssuer = true;
                    }
                } catch (IOException e) {
                    throw new AnnotatedException("CRL issuer information from distribution point cannot be decoded.", e);
                }
            }
        }
        if (matchIssuer && !isIndirect) {
            throw new AnnotatedException("Distribution point contains cRLIssuer field but CRL is not indirect.");
        }
        if (!matchIssuer) {
            throw new AnnotatedException("CRL issuer of CRL does not match CRL issuer of distribution point.");
        }
    } else {
        if (CertPathValidatorUtilities.getIssuerPrincipal(crl).equals(CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert))) {
            matchIssuer = true;
        }
    }
    if (!matchIssuer) {
        throw new AnnotatedException("Cannot find matching CRL issuer for certificate.");
    }
}
Also used : DERObject(org.bouncycastle.asn1.DERObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint)

Example 5 with GeneralName

use of org.bouncycastle.asn1.x509.GeneralName in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCertBC.

protected static void processCertBC(CertPath certPath, int index, PKIXNameConstraintValidator nameConstraintValidator) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    int n = certs.size();
    // i as defined in the algorithm description
    int i = n - index;
    //
    if (!(CertPathValidatorUtilities.isSelfIssued(cert) && (i < n))) {
        X500Principal principal = CertPathValidatorUtilities.getSubjectPrincipal(cert);
        ASN1InputStream aIn = new ASN1InputStream(principal.getEncoded());
        ASN1Sequence dns;
        try {
            dns = DERSequence.getInstance(aIn.readObject());
        } catch (Exception e) {
            throw new CertPathValidatorException("Exception extracting subject name when checking subtrees.", e, certPath, index);
        }
        try {
            nameConstraintValidator.checkPermittedDN(dns);
            nameConstraintValidator.checkExcludedDN(dns);
        } catch (PKIXNameConstraintValidatorException e) {
            throw new CertPathValidatorException("Subtree check for certificate subject failed.", e, certPath, index);
        }
        GeneralNames altName = null;
        try {
            altName = GeneralNames.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME));
        } catch (Exception e) {
            throw new CertPathValidatorException("Subject alternative name extension could not be decoded.", e, certPath, index);
        }
        Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress);
        for (Enumeration e = emails.elements(); e.hasMoreElements(); ) {
            String email = (String) e.nextElement();
            GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email);
            try {
                nameConstraintValidator.checkPermitted(emailAsGeneralName);
                nameConstraintValidator.checkExcluded(emailAsGeneralName);
            } catch (PKIXNameConstraintValidatorException ex) {
                throw new CertPathValidatorException("Subtree check for certificate subject alternative email failed.", ex, certPath, index);
            }
        }
        if (altName != null) {
            GeneralName[] genNames = null;
            try {
                genNames = altName.getNames();
            } catch (Exception e) {
                throw new CertPathValidatorException("Subject alternative name contents could not be decoded.", e, certPath, index);
            }
            for (int j = 0; j < genNames.length; j++) {
                try {
                    nameConstraintValidator.checkPermitted(genNames[j]);
                    nameConstraintValidator.checkExcluded(genNames[j]);
                } catch (PKIXNameConstraintValidatorException e) {
                    throw new CertPathValidatorException("Subtree check for certificate subject alternative name failed.", e, certPath, index);
                }
            }
        }
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) X509Certificate(java.security.cert.X509Certificate) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) 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) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) X509Name(org.bouncycastle.asn1.x509.X509Name) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector)

Aggregations

GeneralName (org.bouncycastle.asn1.x509.GeneralName)149 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)72 IOException (java.io.IOException)58 DERIA5String (org.bouncycastle.asn1.DERIA5String)43 X500Name (org.bouncycastle.asn1.x500.X500Name)38 ArrayList (java.util.ArrayList)37 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)35 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)34 X509Certificate (java.security.cert.X509Certificate)32 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)31 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)31 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)24 BigInteger (java.math.BigInteger)22 List (java.util.List)22 DERSequence (org.bouncycastle.asn1.DERSequence)22 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)21 DirectoryString (org.bouncycastle.asn1.x500.DirectoryString)20 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)19 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19