Search in sources :

Example 1 with JcaX509CertificateHolder

use of org.bouncycastle.cert.jcajce.JcaX509CertificateHolder in project nhin-d by DirectProject.

the class ViewTrustBundlePKCS7 method viewBundle.

@SuppressWarnings({ "rawtypes" })
public boolean viewBundle(File trustDir) {
    try {
        //System.out.println("File:"+trustDir.getName());
        if (!trustDir.getName().endsWith(".p7m")) {
            byte[] trustBundleByte = loadFileData(trustDir);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
            ContentInfo contentInfo = dataParser.getContentInfo();
            SignedData signedData = SignedData.getInstance(contentInfo.getContent());
            Enumeration certificates = signedData.getCertificates().getObjects();
            StringBuffer output = new StringBuffer();
            int counter = 1;
            String chk = "Absent";
            while (certificates.hasMoreElements()) {
                DERObject certObj = (DERObject) certificates.nextElement();
                InputStream in = new ByteArrayInputStream(certObj.getDEREncoded());
                X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
                X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
                RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                output.append("Trust Anchor :" + counter + "\n");
                output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
                output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
                counter++;
            }
            if (signedData.getEncapContentInfo().getContent() != null) {
                //chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
                chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
            }
            output.append("Meta Data :\n" + chk);
            error = output.toString();
        } else //end of if check of file type
        {
            StringBuffer output = new StringBuffer();
            int counter = 1;
            String chk = "Absent";
            byte[] trustBundleByte = loadFileData(trustDir);
            CMSSignedData dataParser = new CMSSignedData(trustBundleByte);
            ContentInfo contentInfo = dataParser.getContentInfo();
            SignedData signedData = SignedData.getInstance(contentInfo.getContent());
            CMSSignedData encapInfoBundle = new CMSSignedData(new CMSProcessableByteArray(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded()), contentInfo);
            SignedData encapMetaData = SignedData.getInstance(encapInfoBundle.getContentInfo().getContent());
            //System.out.println("ENCAP META DATA"+new String(encapMetaData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8"));
            CMSProcessableByteArray cin = new CMSProcessableByteArray(((ASN1OctetString) encapMetaData.getEncapContentInfo().getContent()).getOctets());
            CertificateFactory ucf = CertificateFactory.getInstance("X.509");
            CMSSignedData unsignedParser = new CMSSignedData(cin.getInputStream());
            ContentInfo unsginedEncapInfo = unsignedParser.getContentInfo();
            SignedData metaData = SignedData.getInstance(unsginedEncapInfo.getContent());
            Enumeration certificates = metaData.getCertificates().getObjects();
            while (certificates.hasMoreElements()) {
                DERObject certObj = (DERObject) certificates.nextElement();
                InputStream bin = new ByteArrayInputStream(certObj.getDEREncoded());
                X509Certificate cert = (X509Certificate) ucf.generateCertificate(bin);
                X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
                RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                output.append("Trust Anchor :" + counter + "\n");
                output.append("Common Name :" + IETFUtils.valueToString(cn.getFirst().getValue()) + "\n");
                output.append("DN :" + cert.getSubjectDN().getName() + "\n\n");
                counter++;
            }
            if (metaData.getEncapContentInfo().getContent() != null) {
                //chk = new String(signedData.getEncapContentInfo().getContent().getDERObject().getEncoded(),"UTF-8");
                chk = new String(metaData.getEncapContentInfo().getContent().getDERObject().getDEREncoded(), "UTF-8");
            }
            output.append("Meta Data :\n" + chk);
            error = output.toString();
        }
    //end of .p7m check if
    }//end of try
     catch (IOException io) {
        //io.printStackTrace(System.err);
        return false;
    } catch (CMSException cm) {
        //cm.printStackTrace(System.err);
        return false;
    } catch (Exception e) {
        //e.printStackTrace(System.err);
        return false;
    }
    return true;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) Enumeration(java.util.Enumeration) SignedData(org.bouncycastle.asn1.cms.SignedData) CMSSignedData(org.bouncycastle.cms.CMSSignedData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) CMSSignedData(org.bouncycastle.cms.CMSSignedData) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) IOException(java.io.IOException) DERObject(org.bouncycastle.asn1.DERObject) EncryptedContentInfo(org.bouncycastle.asn1.cms.EncryptedContentInfo) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) RDN(org.bouncycastle.asn1.x500.RDN) CMSException(org.bouncycastle.cms.CMSException)

Example 2 with JcaX509CertificateHolder

use of org.bouncycastle.cert.jcajce.JcaX509CertificateHolder in project nifi by apache.

the class TlsCertificateAuthorityClientSocketFactory method connectSocket.

@Override
public synchronized Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException {
    Socket result = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
    if (!SSLSocket.class.isInstance(result)) {
        throw new IOException("Expected tls socket");
    }
    SSLSocket sslSocket = (SSLSocket) result;
    java.security.cert.Certificate[] peerCertificateChain = sslSocket.getSession().getPeerCertificates();
    if (peerCertificateChain.length != 1) {
        throw new IOException("Expected root ca cert");
    }
    if (!X509Certificate.class.isInstance(peerCertificateChain[0])) {
        throw new IOException("Expected root ca cert in X509 format");
    }
    String cn;
    try {
        X509Certificate certificate = (X509Certificate) peerCertificateChain[0];
        cn = IETFUtils.valueToString(new JcaX509CertificateHolder(certificate).getSubject().getRDNs(BCStyle.CN)[0].getFirst().getValue());
        certificates.add(certificate);
    } catch (Exception e) {
        throw new IOException(e);
    }
    if (!caHostname.equals(cn)) {
        throw new IOException("Expected cn of " + caHostname + " but got " + cn);
    }
    return result;
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) IOException(java.io.IOException) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 3 with JcaX509CertificateHolder

use of org.bouncycastle.cert.jcajce.JcaX509CertificateHolder in project Pix-Art-Messenger by kriztan.

the class CryptoHelper method extractCertificateInformation.

public static Bundle extractCertificateInformation(X509Certificate certificate) {
    Bundle information = new Bundle();
    try {
        JcaX509CertificateHolder holder = new JcaX509CertificateHolder(certificate);
        X500Name subject = holder.getSubject();
        try {
            information.putString("subject_cn", subject.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        try {
            information.putString("subject_o", subject.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        X500Name issuer = holder.getIssuer();
        try {
            information.putString("issuer_cn", issuer.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        try {
            information.putString("issuer_o", issuer.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
        } catch (Exception e) {
        // ignored
        }
        try {
            information.putString("sha1", getFingerprintCert(certificate.getEncoded()));
        } catch (Exception e) {
        }
        return information;
    } catch (CertificateEncodingException e) {
        return information;
    }
}
Also used : Bundle(android.os.Bundle) CertificateEncodingException(java.security.cert.CertificateEncodingException) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) InvalidJidException(de.pixart.messenger.xmpp.jid.InvalidJidException) CertificateParsingException(java.security.cert.CertificateParsingException) MalformedURLException(java.net.MalformedURLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 4 with JcaX509CertificateHolder

use of org.bouncycastle.cert.jcajce.JcaX509CertificateHolder in project Pix-Art-Messenger by kriztan.

the class CryptoHelper method extractJidAndName.

public static Pair<Jid, String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, CertificateParsingException {
    Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
    List<String> emails = new ArrayList<>();
    if (alternativeNames != null) {
        for (List<?> san : alternativeNames) {
            Integer type = (Integer) san.get(0);
            if (type == 1) {
                emails.add((String) san.get(1));
            }
        }
    }
    X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
    if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) {
        emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue()));
    }
    String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
    if (emails.size() >= 1) {
        return new Pair<>(Jid.fromString(emails.get(0)), name);
    } else if (name != null) {
        try {
            Jid jid = Jid.fromString(name);
            if (jid.isBareJid() && !jid.isDomainJid()) {
                return new Pair<>(jid, null);
            }
        } catch (InvalidJidException e) {
            return null;
        }
    }
    return null;
}
Also used : Jid(de.pixart.messenger.xmpp.jid.Jid) InvalidJidException(de.pixart.messenger.xmpp.jid.InvalidJidException) ArrayList(java.util.ArrayList) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) ArrayList(java.util.ArrayList) List(java.util.List) Pair(android.util.Pair)

Example 5 with JcaX509CertificateHolder

use of org.bouncycastle.cert.jcajce.JcaX509CertificateHolder in project oxAuth by GluuFederation.

the class OCSPCertificateVerifier method validate.

@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
    X509Certificate issuer = issuers.get(0);
    ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN);
    try {
        Principal subjectX500Principal = certificate.getSubjectX500Principal();
        String ocspUrl = getOCSPUrl(certificate);
        if (ocspUrl == null) {
            log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
            return status;
        }
        log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");
        DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
        CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());
        // Generate OCSP request
        OCSPReq ocspReq = generateOCSPRequest(certificateId);
        // Get OCSP response from server
        OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
        if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            log.error("OCSP response is invalid!");
            status.setValidity(CertificateValidity.INVALID);
            return status;
        }
        boolean foundResponse = false;
        BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
        SingleResp[] singleResps = basicOCSPResp.getResponses();
        for (SingleResp singleResp : singleResps) {
            CertificateID responseCertificateId = singleResp.getCertID();
            if (!certificateId.equals(responseCertificateId)) {
                continue;
            }
            foundResponse = true;
            log.debug("OCSP validationDate: " + validationDate);
            log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
            log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());
            status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());
            Object certStatus = singleResp.getCertStatus();
            if (certStatus == CertificateStatus.GOOD) {
                log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
                status.setValidity(CertificateValidity.VALID);
            } else {
                if (singleResp.getCertStatus() instanceof RevokedStatus) {
                    log.warn("OCSP status is revoked for: " + subjectX500Principal);
                    if (validationDate.before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
                        log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate);
                        status.setValidity(CertificateValidity.VALID);
                    } else {
                        Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
                        log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate);
                        status.setRevocationDate(revocationDate);
                        status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
                        status.setValidity(CertificateValidity.REVOKED);
                    }
                }
            }
        }
        if (!foundResponse) {
            log.error("There is no matching OCSP response entries");
        }
    } catch (Exception ex) {
        log.error("OCSP exception: ", ex);
    }
    return status;
}
Also used : CertificateID(org.bouncycastle.cert.ocsp.CertificateID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) CertificateEncodingException(java.security.cert.CertificateEncodingException) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ValidationStatus(org.gluu.oxauth.cert.validation.model.ValidationStatus) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) Principal(java.security.Principal)

Aggregations

JcaX509CertificateHolder (org.bouncycastle.cert.jcajce.JcaX509CertificateHolder)24 X500Name (org.bouncycastle.asn1.x500.X500Name)16 CertificateEncodingException (java.security.cert.CertificateEncodingException)13 X509Certificate (java.security.cert.X509Certificate)12 RDN (org.bouncycastle.asn1.x500.RDN)11 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)8 ByteArrayInputStream (java.io.ByteArrayInputStream)5 CertificateFactory (java.security.cert.CertificateFactory)5 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)5 InputStream (java.io.InputStream)4 DERIA5String (org.bouncycastle.asn1.DERIA5String)4 MalformedURLException (java.net.MalformedURLException)3 GeneralSecurityException (java.security.GeneralSecurityException)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 Enumeration (java.util.Enumeration)3 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)3 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)3 Bundle (android.os.Bundle)2