Search in sources :

Example 71 with GeneralNames

use of org.spongycastle.asn1.x509.GeneralNames in project nhin-d by DirectProject.

the class SubjectAltNameExtensionField method injectReferenceValue.

/**
	 * {@inheritDoc}
	 */
@Override
public void injectReferenceValue(X509Certificate value) throws PolicyProcessException {
    this.certificate = value;
    final DERObject exValue = getExtensionValue(value);
    if (exValue == null) {
        if (isRequired())
            throw new PolicyRequiredException("Extention " + getExtentionIdentifier().getDisplay() + " is marked as required by is not present.");
        else {
            final Collection<String> emptyList = Collections.emptyList();
            this.policyValue = PolicyValueFactory.getInstance(emptyList);
            return;
        }
    }
    final Collection<String> names = new ArrayList<String>();
    final GeneralNames generalNames = GeneralNames.getInstance(exValue);
    for (GeneralName name : generalNames.getNames()) {
        final GeneralNameType type = GeneralNameType.fromTag(name.getTagNo());
        if (type != null) {
            names.add(type.getDisplay() + ":" + name.getName().toString());
        }
    }
    this.policyValue = PolicyValueFactory.getInstance(names);
}
Also used : PolicyRequiredException(org.nhindirect.policy.PolicyRequiredException) DERObject(org.bouncycastle.asn1.DERObject) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 72 with GeneralNames

use of org.spongycastle.asn1.x509.GeneralNames in project poi by apache.

the class PkiTestUtils method generateCertificate.

static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore, Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage) throws IOException, OperatorCreationException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X500Name issuerName;
    if (issuerCertificate != null) {
        issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer();
    } else {
        issuerName = new X500Name(subjectDn);
    }
    RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey;
    RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent());
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec);
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName, new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn), subjectPublicKeyInfo);
    X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc);
    SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
    AuthorityKeyIdentifier autKeyId = (issuerCertificate != null) ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded())) : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo);
    certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId);
    certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId);
    if (caFlag) {
        BasicConstraints bc;
        if (-1 == pathLength) {
            bc = new BasicConstraints(true);
        } else {
            bc = new BasicConstraints(pathLength);
        }
        certificateGenerator.addExtension(Extension.basicConstraints, false, bc);
    }
    if (null != crlUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        DERIA5String crlUriDer = new DERIA5String(crlUri);
        GeneralName gn = new GeneralName(uri, crlUriDer);
        DERSequence gnDer = new DERSequence(gn);
        GeneralNames gns = GeneralNames.getInstance(gnDer);
        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        DERSequence distpDer = new DERSequence(distp);
        certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer);
    }
    if (null != ocspUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        GeneralName ocspName = new GeneralName(uri, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }
    if (null != keyUsage) {
        certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage);
    }
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
    signerBuilder.setProvider("BC");
    X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey));
    //                        .getEncoded()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERSequence(org.bouncycastle.asn1.DERSequence) RSAPublicKey(java.security.interfaces.RSAPublicKey) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) SecureRandom(java.security.SecureRandom) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 73 with GeneralNames

use of org.spongycastle.asn1.x509.GeneralNames in project nifi by apache.

the class TlsHelperTest method extractSanFromCsr.

private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }
                sans.add(title + ": " + name.getName());
            }
        }
    }
    return sans;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) Attribute(org.bouncycastle.asn1.pkcs.Attribute) ArrayList(java.util.ArrayList) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions)

Example 74 with GeneralNames

use of org.spongycastle.asn1.x509.GeneralNames in project athenz by yahoo.

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 = null;
    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 (int i = 0; i < names.length; i++) {
                    switch(names[i].getTagNo()) {
                        case GeneralName.dNSName:
                        case GeneralName.iPAddress:
                        case GeneralName.rfc822Name:
                            altNames.add(names[i]);
                            break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }
        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) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) 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) PublicKey(java.security.PublicKey) Calendar(java.util.Calendar) ContentSigner(org.bouncycastle.operator.ContentSigner) InvalidKeyException(java.security.InvalidKeyException) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ECPoint(org.bouncycastle.math.ec.ECPoint) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) FileNotFoundException(java.io.FileNotFoundException) CertificateParsingException(java.security.cert.CertificateParsingException) PEMException(org.bouncycastle.openssl.PEMException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 75 with GeneralNames

use of org.spongycastle.asn1.x509.GeneralNames in project athenz by yahoo.

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);
            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 e) {
                    }
                }
            }
        }
    }
    return ipAddresses;
}
Also used : GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) UnknownHostException(java.net.UnknownHostException) Attribute(org.bouncycastle.asn1.pkcs.Attribute) ArrayList(java.util.ArrayList) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Extensions(org.bouncycastle.asn1.x509.Extensions) InetAddress(java.net.InetAddress)

Aggregations

GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)72 GeneralName (org.bouncycastle.asn1.x509.GeneralName)61 IOException (java.io.IOException)31 X509Certificate (java.security.cert.X509Certificate)22 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)19 DERIA5String (org.bouncycastle.asn1.DERIA5String)15 DEROctetString (org.bouncycastle.asn1.DEROctetString)14 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)14 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)14 Date (java.util.Date)13 List (java.util.List)13 X500Principal (javax.security.auth.x500.X500Principal)12 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)12 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)12 GeneralNames (sun.security.x509.GeneralNames)12 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)11 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)11 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)11 Test (org.junit.Test)11