Search in sources :

Example 6 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project OpenAttestation by OpenAttestation.

the class ProvisionTagCertificate method certificateAttributesEqual.

//    
//    /**
//     * Check that the attributes in the certificate are the same as the attributes in the given selection.
//     * The order is not considered so they do not have to be in the same order.
//     * 
//     * The given selection must have inline attributes (not requiring any lookup by id or name).
//     * 
//     * @return true if the attribute certificate has exactly the same attributes as in the given selection
//     */
protected boolean certificateAttributesEqual(X509AttributeCertificate certificate, SelectionType selection) throws IOException {
    List<Attribute> certAttributes = certificate.getAttribute();
    // initialized with all false, later we mark individual elements true if they are found within the given selection, so that if any are left false at the end we know that there are attributes in the cert that were not in the selection
    boolean[] certAttrMatch = new boolean[certAttributes.size()];
    // for every attribute in the selection, check if it's present in the certificate 
    for (AttributeType xmlAttribute : selection.getAttribute()) {
        X509AttrBuilder.Attribute oidAndValue = Util.toAttributeOidValue(xmlAttribute);
        // look through the certificate for same oid and value
        boolean found = false;
        for (int i = 0; i < certAttrMatch.length; i++) {
            if (Arrays.equals(certAttributes.get(i).getAttrType().getDEREncoded(), oidAndValue.oid.getDEREncoded())) {
                if (Arrays.equals(certAttributes.get(i).getAttributeValues()[0].getDEREncoded(), oidAndValue.value.getDEREncoded())) {
                    certAttrMatch[i] = true;
                    found = true;
                }
            }
        }
        if (!found) {
            log.debug("Certificate does not have attribute oid {} and value {}", Hex.encodeHexString(oidAndValue.oid.getDEREncoded()), Hex.encodeHexString(oidAndValue.value.getDEREncoded()));
            return false;
        }
    }
    // check if the certificate has any attributes that are not in the selection 
    for (int i = 0; i < certAttrMatch.length; i++) {
        if (!certAttrMatch[i]) {
            log.debug("Selection does not have attribute oid {} and value {}", Hex.encodeHexString(certAttributes.get(i).getAttrType().getDEREncoded()), Hex.encodeHexString(certAttributes.get(i).getAttributeValues()[0].getDEREncoded()));
            return false;
        }
    }
    // certificate and selection have same set of attribute (oid,value) pairs
    return true;
}
Also used : Attribute(org.bouncycastle.asn1.x509.Attribute) AttributeType(com.intel.mtwilson.tag.selection.xml.AttributeType) X509AttrBuilder(com.intel.mtwilson.tag.common.X509AttrBuilder)

Example 7 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCRLF.

/**
     * Obtain and validate the certification path for the complete CRL issuer.
     * If a key usage extension is present in the CRL issuer's certificate,
     * verify that the cRLSign bit is set.
     *
     * @param crl                CRL which contains revocation information for the certificate
     *                           <code>cert</code>.
     * @param cert               The attribute certificate or certificate to check if it is
     *                           revoked.
     * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
     * @param defaultCRLSignKey  The public key of the issuer certificate
     *                           <code>defaultCRLSignCert</code>.
     * @param paramsPKIX         paramsPKIX PKIX parameters.
     * @param certPathCerts      The certificates on the certification path.
     * @return A <code>Set</code> with all keys of possible CRL issuer
     *         certificates.
     * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
     *                            some error occurs.
     */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertStoreSelector selector = new X509CertStoreSelector();
    try {
        byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
        selector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    // get CRL signing certs
    Collection coll;
    try {
        coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
             * CA of the certificate, for which this CRL is checked, has also
             * signed CRL, so skip the path validation, because is already done
             */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
            selector = new X509CertStoreSelector();
            selector.setCertificate(signingCert);
            ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
            temp.setTargetCertConstraints(selector);
            ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
            /*
                 * if signingCert is placed not higher on the cert path a
                 * dependency loop results. CRL for cert is checked, but
                 * signingCert is needed for checking the CRL which is dependent
                 * on checking cert because it is higher in the cert path and so
                 * signing signingCert transitively. so, revocation is disabled,
                 * forgery attacks of the CRL are detected in this outer loop
                 * for all other it must be enabled to prevent forgery attacks
                 */
            if (certPathCerts.contains(signingCert)) {
                params.setRevocationEnabled(false);
            } else {
                params.setRevocationEnabled(true);
            }
            List certs = builder.build(params).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("Internal error.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyusage = signCert.getKeyUsage();
        if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ExtendedPKIXBuilderParameters(org.bouncycastle.x509.ExtendedPKIXBuilderParameters) X509CertStoreSelector(org.bouncycastle.x509.X509CertStoreSelector) ArrayList(java.util.ArrayList) IOException(java.io.IOException) 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) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet)

Example 8 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute 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 9 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project nhin-d by DirectProject.

the class CertGenerator method createCertFromCSR.

public static X509Certificate createCertFromCSR(PKCS10CertificationRequest certReq, CertCreateFields signerCert) throws Exception {
    certReq.verify();
    final CertificationRequestInfo reqInfo = certReq.getCertificationRequestInfo();
    final X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    final Calendar start = Calendar.getInstance();
    final Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 3);
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    // issuer is the parent cert
    v1CertGen.setIssuerDN(signerCert.getSignerCert().getSubjectX500Principal());
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    v1CertGen.setSubjectDN(new X509Principal(reqInfo.getSubject().toString()));
    v1CertGen.setPublicKey(certReq.getPublicKey());
    v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    final ASN1Set attributesAsn1Set = reqInfo.getAttributes();
    X509Extensions certificateRequestExtensions = null;
    for (int i = 0; i < attributesAsn1Set.size(); ++i) {
        // There should be only only one attribute in the set. (that is, only
        // the `Extension Request`, but loop through to find it properly)
        final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
        if (derEncodable instanceof DERSequence) {
            final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));
            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // The `Extension Request` attribute is present.
                final ASN1Set attributeValues = attribute.getAttrValues();
                // Assume that it is the first value of the set.
                if (attributeValues.size() >= 1) {
                    certificateRequestExtensions = new X509Extensions((ASN1Sequence) attributeValues.getObjectAt(0));
                // No need to search any more.
                //break;
                }
            }
        }
    }
    @SuppressWarnings("unchecked") Enumeration<DERObjectIdentifier> oids = certificateRequestExtensions.oids();
    while (oids.hasMoreElements()) {
        DERObjectIdentifier oid = oids.nextElement();
        X509Extension ex = certificateRequestExtensions.getExtension(oid);
        v1CertGen.addExtension(oid, ex.isCritical(), X509Extension.convertValueToObject(ex));
    }
    return v1CertGen.generate((PrivateKey) signerCert.getSignerKey(), CryptoExtensions.getJCEProviderName());
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.cms.Attribute) X509Extension(org.bouncycastle.asn1.x509.X509Extension) Calendar(java.util.Calendar) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) X509Principal(org.bouncycastle.jce.X509Principal) DEREncodable(org.bouncycastle.asn1.DEREncodable)

Example 10 with Attribute

use of org.bouncycastle.asn1.pkcs.Attribute in project nhin-d by DirectProject.

the class TrustChainValidator method getIssuerAddress.

private String getIssuerAddress(X509Certificate certificate) {
    String address = "";
    // check alternative names first
    Collection<List<?>> altNames = null;
    try {
        altNames = certificate.getIssuerAlternativeNames();
    } catch (CertificateParsingException ex) {
    /* no -op */
    }
    if (altNames != null) {
        for (List<?> entries : altNames) {
            if (// should always be the case according the altNames spec, but checking to be defensive
            entries.size() >= 2) {
                Integer nameType = (Integer) entries.get(0);
                // prefer email over over domain?
                if (nameType == RFC822Name_TYPE)
                    address = (String) entries.get(1);
                else if (nameType == DNSName_TYPE && address.isEmpty())
                    address = (String) entries.get(1);
            }
        }
    }
    if (!address.isEmpty())
        return address;
    // can't find issuer address in alt names... try the principal 
    X500Principal issuerPrin = certificate.getIssuerX500Principal();
    // get the domain name
    Map<String, String> oidMap = new HashMap<String, String>();
    // OID for email address
    oidMap.put("1.2.840.113549.1.9.1", "EMAILADDRESS");
    String prinName = issuerPrin.getName(X500Principal.RFC1779, oidMap);
    // see if there is an email address first in the DN
    String searchString = "EMAILADDRESS=";
    int index = prinName.indexOf(searchString);
    if (index == -1) {
        searchString = "CN=";
        // no Email.. check the CN
        index = prinName.indexOf(searchString);
        if (index == -1)
            // no CN... nothing else that can be done from here
            return "";
    }
    // look for a "," to find the end of this attribute
    int endIndex = prinName.indexOf(",", index);
    if (endIndex > -1)
        address = prinName.substring(index + searchString.length(), endIndex);
    else
        address = prinName.substring(index + searchString.length());
    return address;
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) HashMap(java.util.HashMap) X500Principal(javax.security.auth.x500.X500Principal) ArrayList(java.util.ArrayList) List(java.util.List) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) Thumbprint(org.nhindirect.stagent.cert.Thumbprint)

Aggregations

ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)18 IOException (java.io.IOException)16 ArrayList (java.util.ArrayList)13 List (java.util.List)11 Attribute (org.bouncycastle.asn1.cms.Attribute)10 X509Certificate (java.security.cert.X509Certificate)9 DEROctetString (org.bouncycastle.asn1.DEROctetString)9 DERSequence (org.bouncycastle.asn1.DERSequence)9 GeneralName (org.bouncycastle.asn1.x509.GeneralName)9 Iterator (java.util.Iterator)8 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)8 DERObject (org.bouncycastle.asn1.DERObject)8 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)6 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)6 ASN1Set (org.bouncycastle.asn1.ASN1Set)6 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)6 Enumeration (java.util.Enumeration)5 X500Principal (javax.security.auth.x500.X500Principal)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Vector (java.util.Vector)4