Search in sources :

Example 81 with DEROctetString

use of com.github.zhenwei.core.asn1.DEROctetString in project module-ballerina-http by ballerina-platform.

the class OCSPVerifier method generateOCSPRequest.

/**
 * This method generates an OCSP Request to be sent to an OCSP authority access endpoint.
 *
 * @param issuerCert the Issuer's certificate of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request.
 * @throws CertificateVerificationException if any error occurs while generating ocsp request.
 */
public static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws CertificateVerificationException {
    // Programatically adding Bouncy Castle as the security provider. So no need to manually set. Once the programme
    // is over security provider will also be removed.
    Security.addProvider(new BouncyCastleProvider());
    try {
        byte[] issuerCertEnc = issuerCert.getEncoded();
        X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(Constants.BOUNCY_CASTLE_PROVIDER).build();
        // CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560.
        CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, serialNumber);
        // basic request generation with nonce.
        OCSPReqBuilder builder = new OCSPReqBuilder();
        builder.addRequest(id);
        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent re-play attacks. As the name implies,
        // the nonce value is something that the client should only use once during a reasonably small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        // to create the request Extension
        builder.setRequestExtensions(new Extensions(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce.toByteArray()))));
        return builder.build();
    } catch (OCSPException | OperatorCreationException | IOException | CertificateEncodingException e) {
        throw new CertificateVerificationException("Cannot generate OCSP Request with the given certificate", e);
    }
}
Also used : CertificateID(org.bouncycastle.cert.ocsp.CertificateID) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) DEROctetString(org.bouncycastle.asn1.DEROctetString) Extension(org.bouncycastle.asn1.x509.Extension) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CertificateVerificationException(io.ballerina.stdlib.http.transport.contractimpl.common.certificatevalidation.CertificateVerificationException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 82 with DEROctetString

use of com.github.zhenwei.core.asn1.DEROctetString in project module-ballerina-http by ballerina-platform.

the class CRLVerifier method getCrlDistributionPoints.

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point"
 * extension in a X.509 certificate. If CRL distribution point extension is
 * unavailable, returns an empty list.
 */
private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException {
    // Gets the DER-encoded OCTET string for the extension value for CRLDistributionPoints.
    byte[] crlDPExtensionValue = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crlDPExtensionValue == null) {
        throw new CertificateVerificationException("Certificate doesn't have CRL distribution points");
    }
    // crlDPExtensionValue is encoded in ASN.1 format.
    ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue);
    // DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690, 2002, specification.
    // ASN.1 encoding rules can be used to encode any data object into a binary file. Read the object in octets.
    CRLDistPoint distPoint;
    try {
        DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject();
        // Get Input stream in octets.
        distPoint = getOctetInputStream(crlDEROctetString);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get CRL URLs", e);
    } finally {
        try {
            asn1In.close();
        } catch (IOException e) {
            LOG.error("Cannot close input stream", e);
        }
    }
    List<String> crlUrls = new ArrayList<>();
    // Loop through ASN1Encodable DistributionPoints.
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        // get ASN1Encodable DistributionPointName.
        DistributionPointName dpn = dp.getDistributionPoint();
        if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
            // Create ASN1Encodable General Names.
            GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
            // Look for a URI
            for (GeneralName genName : genNames) {
                if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                    // DERIA5String contains an ascii string.
                    // A IA5String is a restricted character string type in the ASN.1 notation.
                    String url = DERIA5String.getInstance(genName.getName()).getString().trim();
                    crlUrls.add(url);
                }
            }
        }
    }
    if (crlUrls.isEmpty()) {
        throw new CertificateVerificationException("Cant get CRL urls from certificate");
    }
    return crlUrls;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ArrayList(java.util.ArrayList) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) IOException(java.io.IOException) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DEROctetString(org.bouncycastle.asn1.DEROctetString) CertificateVerificationException(io.ballerina.stdlib.http.transport.contractimpl.common.certificatevalidation.CertificateVerificationException) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralName(org.bouncycastle.asn1.x509.GeneralName) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 83 with DEROctetString

use of com.github.zhenwei.core.asn1.DEROctetString in project module-ballerina-http by ballerina-platform.

the class OCSPVerifier method getAIALocations.

/**
 * Authority Information Access (AIA) is a non-critical extension in an X509 Certificate. This contains the
 * URL of the OCSP endpoint if one is available.
 *
 * @param cert is the certificate
 * @return a lit of URLs in AIA extension of the certificate which will hopefully contain an OCSP endpoint.
 * @throws CertificateVerificationException if any error occurs while retrieving authority access points from the
 * certificate.
 */
public static List<String> getAIALocations(X509Certificate cert) throws CertificateVerificationException {
    // Gets the DER-encoded OCTET string for the extension value for Authority information access points.
    byte[] aiaExtensionValue = cert.getExtensionValue(Extension.authorityInfoAccess.getId());
    if (aiaExtensionValue == null) {
        throw new CertificateVerificationException("Certificate doesn't have Authority Information Access points");
    }
    AuthorityInformationAccess authorityInformationAccess;
    ASN1InputStream asn1InputStream = null;
    try {
        DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(aiaExtensionValue)).readObject());
        asn1InputStream = new ASN1InputStream(oct.getOctets());
        authorityInformationAccess = AuthorityInformationAccess.getInstance(asn1InputStream.readObject());
    } catch (IOException e) {
        throw new CertificateVerificationException("Cannot read certificate to get OSCP urls", e);
    } finally {
        try {
            if (asn1InputStream != null) {
                asn1InputStream.close();
            }
        } catch (IOException e) {
            LOG.error("Cannot close ASN1InputStream", e);
        }
    }
    List<String> ocspUrlList = new ArrayList<>();
    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {
        GeneralName gn = accessDescription.getAccessLocation();
        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
            DERIA5String str = DERIA5String.getInstance(gn.getName());
            String accessLocation = str.getString();
            ocspUrlList.add(accessLocation);
        }
    }
    if (ocspUrlList.isEmpty()) {
        throw new CertificateVerificationException("Cannot get OCSP urls from certificate");
    }
    return ocspUrlList;
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) CertificateVerificationException(io.ballerina.stdlib.http.transport.contractimpl.common.certificatevalidation.CertificateVerificationException) ByteArrayInputStream(java.io.ByteArrayInputStream) AccessDescription(org.bouncycastle.asn1.x509.AccessDescription) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 84 with DEROctetString

use of com.github.zhenwei.core.asn1.DEROctetString in project mucommander by mucommander.

the class CRLVerifier method getCrlDistributionPoints.

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point"
 * extension in a X.509 certificate. If CRL distribution point extension is
 * unavailable, returns an empty list.
 */
public static List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateParsingException, IOException {
    byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (crldpExt == null) {
        return new ArrayList<String>();
    }
    ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt));
    ASN1Primitive derObjCrlDP = oAsnInStream.readObject();
    DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP;
    byte[] crldpExtOctets = dosCrlDP.getOctets();
    ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets));
    ASN1Primitive derObj2 = oAsnInStream2.readObject();
    CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2);
    List<String> crlUrls = new ArrayList<String>();
    for (DistributionPoint dp : distPoint.getDistributionPoints()) {
        DistributionPointName dpn = dp.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null) {
            if (dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                // Look for an URI
                for (GeneralName genName : genNames) {
                    if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = DERIA5String.getInstance(genName.getName()).getString();
                        crlUrls.add(url);
                    }
                }
            }
        }
    }
    return crlUrls;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ArrayList(java.util.ArrayList) DERIA5String(org.bouncycastle.asn1.DERIA5String) DEROctetString(org.bouncycastle.asn1.DEROctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 85 with DEROctetString

use of com.github.zhenwei.core.asn1.DEROctetString in project daikon by Talend.

the class CertificateGenerater method createRootCA.

private void createRootCA(String alias, String fileName) throws Exception {
    List<Extension> exts = new ArrayList<>();
    KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyCertSign);
    Extension extension = new Extension(Extension.keyUsage, true, new DEROctetString(keyUsage));
    exts.add(extension);
    // Missing ekeyOid = new ObjectIdentifier("2.5.29.19"); from the old code here
    ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning);
    extension = new Extension(Extension.extendedKeyUsage, false, new DEROctetString(extendedKeyUsage));
    exts.add(extension);
    KeyPair keyPair = genKey();
    BigInteger serialNumber = new BigInteger(64, secureRandom);
    Date from = new Date();
    Date to = new Date(from.getTime() + 365L * 24 * 3600 * 1000);
    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(new X500Principal(dName), serialNumber, from, to, new X500Principal(dName), keyPair.getPublic());
    for (Extension e : exts) {
        certificateBuilder.addExtension(e);
    }
    certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    ContentSigner signer = new JcaContentSignerBuilder(sigAlgName).build(keyPair.getPrivate());
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certificateBuilder.build(signer));
    X509Certificate[] certs = { cert };
    String[] aliasNames = { alias };
    saveJks(aliasNames, keyPair.getPrivate(), rootJKSKeyPass, certs, fileName);
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) DEROctetString(org.bouncycastle.asn1.DEROctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Extension(org.bouncycastle.asn1.x509.Extension) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) X500Principal(javax.security.auth.x500.X500Principal) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

DEROctetString (org.bouncycastle.asn1.DEROctetString)139 IOException (java.io.IOException)104 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)86 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)49 DERSequence (org.bouncycastle.asn1.DERSequence)48 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)46 DERSequence (com.github.zhenwei.core.asn1.DERSequence)44 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)39 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)32 BigInteger (java.math.BigInteger)27 Extension (org.bouncycastle.asn1.x509.Extension)27 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)26 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)26 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)24 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)23 DERTaggedObject (org.bouncycastle.asn1.DERTaggedObject)21 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)19 Extensions (org.bouncycastle.asn1.x509.Extensions)19 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)18