Search in sources :

Example 86 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project athenz by AthenZ.

the class Crypto method extractX509CSRIPAddresses.

public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {
    List<String> ipAddresses = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            if (gns == null) {
                continue;
            }
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.iPAddress) {
                    try {
                        InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets());
                        ipAddresses.add(addr.getHostAddress());
                    } catch (UnknownHostException ignored) {
                    }
                }
            }
        }
    }
    return ipAddresses;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) UnknownHostException(java.net.UnknownHostException) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions) InetAddress(java.net.InetAddress)

Example 87 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project athenz by AthenZ.

the class Crypto method generateX509Certificate.

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {
    // set validity for the given number of minutes from now
    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();
    // Generate self-signed certificate
    X509Certificate cert;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();
        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(), publicKey).addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints)).addExtension(Extension.keyUsage, true, new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment)).addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // see if we have the dns/rfc822/ip address extensions specified in the csr
        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (GeneralName name : names) {
                    switch(name.getTagNo()) {
                        case GeneralName.dNSName:
                        case GeneralName.iPAddress:
                        case GeneralName.rfc822Name:
                        case GeneralName.uniformResourceIdentifier:
                            altNames.add(name);
                            break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[0])));
            }
        }
        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER).build(caPrivateKey);
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));
    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error("generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error("generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: " + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: {}", ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }
    return cert;
}
Also used : Attribute(org.bouncycastle.asn1.pkcs.Attribute) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Extensions(org.bouncycastle.asn1.x509.Extensions) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509KeyUsage(org.bouncycastle.jce.X509KeyUsage) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) ContentSigner(org.bouncycastle.operator.ContentSigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMException(org.bouncycastle.openssl.PEMException) UnknownHostException(java.net.UnknownHostException) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 88 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project athenz by AthenZ.

the class Crypto method extractX509CSRSANField.

private static List<String> extractX509CSRSANField(PKCS10CertificationRequest certReq, int tagNo) {
    List<String> values = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            if (gns == null) {
                continue;
            }
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == tagNo) {
                    values.add(((DERIA5String) name.getName()).getString());
                }
            }
        }
    }
    return values;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions)

Example 89 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project LinLong-Java by zhenwei1108.

the class ResponseData method toASN1Primitive.

/**
 * Produce an object suitable for an ASN1OutputStream.
 * <pre>
 * ResponseData ::= SEQUENCE {
 *     version              [0] EXPLICIT Version DEFAULT v1,
 *     responderID              ResponderID,
 *     producedAt               GeneralizedTime,
 *     responses                SEQUENCE OF SingleResponse,
 *     responseExtensions   [1] EXPLICIT Extensions OPTIONAL }
 * </pre>
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(5);
    if (versionPresent || !version.equals(V1)) {
        v.add(new DERTaggedObject(true, 0, version));
    }
    v.add(responderID);
    v.add(producedAt);
    v.add(responses);
    if (responseExtensions != null) {
        v.add(new DERTaggedObject(true, 1, responseExtensions));
    }
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) DERTaggedObject(com.github.zhenwei.core.asn1.DERTaggedObject) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 90 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project LinLong-Java by zhenwei1108.

the class SingleResponse method toASN1Primitive.

/**
 * Produce an object suitable for an ASN1OutputStream.
 * <pre>
 *  SingleResponse ::= SEQUENCE {
 *          certID                       CertID,
 *          certStatus                   CertStatus,
 *          thisUpdate                   GeneralizedTime,
 *          nextUpdate         [0]       EXPLICIT GeneralizedTime OPTIONAL,
 *          singleExtensions   [1]       EXPLICIT Extensions OPTIONAL }
 * </pre>
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(5);
    v.add(certID);
    v.add(certStatus);
    v.add(thisUpdate);
    if (nextUpdate != null) {
        v.add(new DERTaggedObject(true, 0, nextUpdate));
    }
    if (singleExtensions != null) {
        v.add(new DERTaggedObject(true, 1, singleExtensions));
    }
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) DERTaggedObject(com.github.zhenwei.core.asn1.DERTaggedObject) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Aggregations

Extensions (org.bouncycastle.asn1.x509.Extensions)113 Extension (org.bouncycastle.asn1.x509.Extension)89 IOException (java.io.IOException)72 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Enumeration (java.util.Enumeration)57 HashSet (java.util.HashSet)49 DEROctetString (org.bouncycastle.asn1.DEROctetString)49 X500Name (org.bouncycastle.asn1.x500.X500Name)46 BigInteger (java.math.BigInteger)45 Set (java.util.Set)36 X509Certificate (java.security.cert.X509Certificate)35 Date (java.util.Date)35 GeneralName (org.bouncycastle.asn1.x509.GeneralName)35 ContentSigner (org.bouncycastle.operator.ContentSigner)32 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)29 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)28 ArrayList (java.util.ArrayList)28 CertificateException (java.security.cert.CertificateException)27 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)27