Search in sources :

Example 46 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute in project LinLong-Java by zhenwei1108.

the class PKCS12SafeBag method getAttributes.

public Attribute[] getAttributes() {
    ASN1Set attrs = safeBag.getBagAttributes();
    if (attrs == null) {
        return null;
    }
    Attribute[] attributes = new Attribute[attrs.size()];
    for (int i = 0; i != attrs.size(); i++) {
        attributes[i] = Attribute.getInstance(attrs.getObjectAt(i));
    }
    return attributes;
}
Also used : ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) Attribute(com.github.zhenwei.core.asn1.pkcs.Attribute)

Example 47 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute in project LinLong-Java by zhenwei1108.

the class CertPathValidatorUtilities method getCRLIssuersFromDistributionPoint.

/**
 * Add the CRL issuers from the cRLIssuer field of the distribution point or from the certificate
 * if not given to the issuer criterion of the
 * <code>selector</code>.
 * <p>
 * The <code>issuerPrincipals</code> are a collection with a single
 * <code>X500Name</code> for <code>X509Certificate</code>s.
 * </p>
 *
 * @param dp               The distribution point.
 * @param issuerPrincipals The issuers of the certificate or attribute certificate which contains
 *                         the distribution point.
 * @param selector         The CRL selector.
 * @throws AnnotatedException if an exception occurs while processing.
 * @throws ClassCastException if <code>issuerPrincipals</code> does not contain only
 *                            <code>X500Name</code>s.
 */
protected static void getCRLIssuersFromDistributionPoint(DistributionPoint dp, Collection issuerPrincipals, X509CRLSelector selector) throws AnnotatedException {
    List issuers = new ArrayList();
    // indirect CRL
    if (dp.getCRLIssuer() != null) {
        GeneralName[] genNames = dp.getCRLIssuer().getNames();
        // look for a DN
        for (int j = 0; j < genNames.length; j++) {
            if (genNames[j].getTagNo() == GeneralName.directoryName) {
                try {
                    issuers.add(X500Name.getInstance(genNames[j].getName().toASN1Primitive().getEncoded()));
                } catch (IOException e) {
                    throw new AnnotatedException("CRL issuer information from distribution point cannot be decoded.", e);
                }
            }
        }
    } else {
        /*
       * certificate issuer is CRL issuer, distributionPoint field MUST be
       * present.
       */
        if (dp.getDistributionPoint() == null) {
            throw new AnnotatedException("CRL issuer is omitted from distribution point but no distributionPoint field present.");
        }
        // add and check issuer principals
        for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) {
            issuers.add(it.next());
        }
    }
    // TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
    // distributionPoint
    // if (dp.getDistributionPoint() != null)
    // {
    // // look for nameRelativeToCRLIssuer
    // if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
    // {
    // // append fragment to issuer, only one
    // // issuer can be there, if this is given
    // if (issuers.size() != 1)
    // {
    // throw new AnnotatedException(
    // "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
    // }
    // ASN1Encodable relName = dp.getDistributionPoint().getName();
    // Iterator it = issuers.iterator();
    // List issuersTemp = new ArrayList(issuers.size());
    // while (it.hasNext())
    // {
    // Enumeration e = null;
    // try
    // {
    // e = ASN1Sequence.getInstance(
    // new ASN1InputStream(((X500Principal) it.next())
    // .getEncoded()).readObject()).getObjects();
    // }
    // catch (IOException ex)
    // {
    // throw new AnnotatedException(
    // "Cannot decode CRL issuer information.", ex);
    // }
    // ASN1EncodableVector v = new ASN1EncodableVector();
    // while (e.hasMoreElements())
    // {
    // v.add((ASN1Encodable) e.nextElement());
    // }
    // v.add(relName);
    // issuersTemp.add(new X500Principal(new DERSequence(v)
    // .getDEREncoded()));
    // }
    // issuers.clear();
    // issuers.addAll(issuersTemp);
    // }
    // }
    Iterator it = issuers.iterator();
    while (it.hasNext()) {
        try {
            selector.addIssuerName(((X500Name) it.next()).getEncoded());
        } catch (IOException ex) {
            throw new AnnotatedException("Cannot decode CRL issuer information.", ex);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) IOException(java.io.IOException) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint)

Example 48 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute 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;
    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);
                // /CLOVER:OFF
                if (gns == null) {
                    continue;
                }
                // /CLOVER:ON
                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));
    // /CLOVER:OFF
    } 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");
    }
    // /CLOVER:ON
    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 49 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute 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);
            // /CLOVER:OFF
            if (gns == null) {
                continue;
            }
            // /CLOVER:ON
            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 50 with Attribute

use of com.github.zhenwei.core.asn1.pkcs.Attribute 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)

Aggregations

Attribute (org.bouncycastle.asn1.pkcs.Attribute)36 IOException (java.io.IOException)25 Extensions (org.bouncycastle.asn1.x509.Extensions)18 ArrayList (java.util.ArrayList)17 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)15 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)13 List (java.util.List)12 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)12 GeneralName (org.bouncycastle.asn1.x509.GeneralName)12 ASN1Set (org.bouncycastle.asn1.ASN1Set)10 ASN1Set (com.github.zhenwei.core.asn1.ASN1Set)9 Iterator (java.util.Iterator)9 CRLDistPoint (com.github.zhenwei.core.asn1.x509.CRLDistPoint)8 DistributionPoint (com.github.zhenwei.core.asn1.x509.DistributionPoint)8 AttributeTable (com.github.zhenwei.pkix.util.asn1.cms.AttributeTable)8 Enumeration (java.util.Enumeration)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 Attribute (com.github.zhenwei.pkix.util.asn1.cms.Attribute)7 GeneralName (com.github.zhenwei.core.asn1.x509.GeneralName)6 GeneralSecurityException (java.security.GeneralSecurityException)6