Search in sources :

Example 46 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method processCertD.

protected static PKIXPolicyNode processCertD(CertPath certPath, int index, Set acceptablePolicies, PKIXPolicyNode validPolicyTree, List[] policyNodes, int inhibitAnyPolicy) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    int n = certs.size();
    // i as defined in the algorithm description
    int i = n - index;
    //
    // (d) policy Information checking against initial policy and
    // policy mapping
    //
    ASN1Sequence certPolicies = null;
    try {
        certPolicies = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.CERTIFICATE_POLICIES));
    } catch (AnnotatedException e) {
        throw new ExtCertPathValidatorException("Could not read certificate policies extension from certificate.", e, certPath, index);
    }
    if (certPolicies != null && validPolicyTree != null) {
        //
        // (d) (1)
        //
        Enumeration e = certPolicies.getObjects();
        Set pols = new HashSet();
        while (e.hasMoreElements()) {
            PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement());
            DERObjectIdentifier pOid = pInfo.getPolicyIdentifier();
            pols.add(pOid.getId());
            if (!RFC3280CertPathUtilities.ANY_POLICY.equals(pOid.getId())) {
                Set pq = null;
                try {
                    pq = CertPathValidatorUtilities.getQualifierSet(pInfo.getPolicyQualifiers());
                } catch (CertPathValidatorException ex) {
                    throw new ExtCertPathValidatorException("Policy qualifier info set could not be build.", ex, certPath, index);
                }
                boolean match = CertPathValidatorUtilities.processCertD1i(i, policyNodes, pOid, pq);
                if (!match) {
                    CertPathValidatorUtilities.processCertD1ii(i, policyNodes, pOid, pq);
                }
            }
        }
        if (acceptablePolicies.isEmpty() || acceptablePolicies.contains(RFC3280CertPathUtilities.ANY_POLICY)) {
            acceptablePolicies.clear();
            acceptablePolicies.addAll(pols);
        } else {
            Iterator it = acceptablePolicies.iterator();
            Set t1 = new HashSet();
            while (it.hasNext()) {
                Object o = it.next();
                if (pols.contains(o)) {
                    t1.add(o);
                }
            }
            acceptablePolicies.clear();
            acceptablePolicies.addAll(t1);
        }
        //
        if ((inhibitAnyPolicy > 0) || ((i < n) && CertPathValidatorUtilities.isSelfIssued(cert))) {
            e = certPolicies.getObjects();
            while (e.hasMoreElements()) {
                PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement());
                if (RFC3280CertPathUtilities.ANY_POLICY.equals(pInfo.getPolicyIdentifier().getId())) {
                    Set _apq = CertPathValidatorUtilities.getQualifierSet(pInfo.getPolicyQualifiers());
                    List _nodes = policyNodes[i - 1];
                    for (int k = 0; k < _nodes.size(); k++) {
                        PKIXPolicyNode _node = (PKIXPolicyNode) _nodes.get(k);
                        Iterator _policySetIter = _node.getExpectedPolicies().iterator();
                        while (_policySetIter.hasNext()) {
                            Object _tmp = _policySetIter.next();
                            String _policy;
                            if (_tmp instanceof String) {
                                _policy = (String) _tmp;
                            } else if (_tmp instanceof DERObjectIdentifier) {
                                _policy = ((DERObjectIdentifier) _tmp).getId();
                            } else {
                                continue;
                            }
                            boolean _found = false;
                            Iterator _childrenIter = _node.getChildren();
                            while (_childrenIter.hasNext()) {
                                PKIXPolicyNode _child = (PKIXPolicyNode) _childrenIter.next();
                                if (_policy.equals(_child.getValidPolicy())) {
                                    _found = true;
                                }
                            }
                            if (!_found) {
                                Set _newChildExpectedPolicies = new HashSet();
                                _newChildExpectedPolicies.add(_policy);
                                PKIXPolicyNode _newChild = new PKIXPolicyNode(new ArrayList(), i, _newChildExpectedPolicies, _node, _apq, _policy, false);
                                _node.addChild(_newChild);
                                policyNodes[i].add(_newChild);
                            }
                        }
                    }
                    break;
                }
            }
        }
        PKIXPolicyNode _validPolicyTree = validPolicyTree;
        //
        for (int j = (i - 1); j >= 0; j--) {
            List nodes = policyNodes[j];
            for (int k = 0; k < nodes.size(); k++) {
                PKIXPolicyNode node = (PKIXPolicyNode) nodes.get(k);
                if (!node.hasChildren()) {
                    _validPolicyTree = CertPathValidatorUtilities.removePolicyNode(_validPolicyTree, policyNodes, node);
                    if (_validPolicyTree == null) {
                        break;
                    }
                }
            }
        }
        //
        // d (4)
        //
        Set criticalExtensionOids = cert.getCriticalExtensionOIDs();
        if (criticalExtensionOids != null) {
            boolean critical = criticalExtensionOids.contains(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
            List nodes = policyNodes[i];
            for (int j = 0; j < nodes.size(); j++) {
                PKIXPolicyNode node = (PKIXPolicyNode) nodes.get(j);
                node.setCritical(critical);
            }
        }
        return _validPolicyTree;
    }
    return null;
}
Also used : Enumeration(java.util.Enumeration) Set(java.util.Set) HashSet(java.util.HashSet) PolicyInformation(org.bouncycastle.asn1.x509.PolicyInformation) ArrayList(java.util.ArrayList) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) DERObject(org.bouncycastle.asn1.DERObject) HashSet(java.util.HashSet)

Example 47 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method prepareNextCertJ.

protected static int prepareNextCertJ(CertPath certPath, int index, int inhibitAnyPolicy) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    //
    // (j)
    //
    DERInteger iap = null;
    try {
        iap = DERInteger.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.INHIBIT_ANY_POLICY));
    } catch (Exception e) {
        throw new ExtCertPathValidatorException("Inhibit any-policy extension cannot be decoded.", e, certPath, index);
    }
    if (iap != null) {
        int _inhibitAnyPolicy = iap.getValue().intValue();
        if (_inhibitAnyPolicy < inhibitAnyPolicy) {
            return _inhibitAnyPolicy;
        }
    }
    return inhibitAnyPolicy;
}
Also used : ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) List(java.util.List) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) DERInteger(org.bouncycastle.asn1.DERInteger)

Example 48 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project robovm by robovm.

the class X509CertificateObject method toString.

public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("  [0]         Version: ").append(this.getVersion()).append(nl);
    buf.append("         SerialNumber: ").append(this.getSerialNumber()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("           Start Date: ").append(this.getNotBefore()).append(nl);
    buf.append("           Final Date: ").append(this.getNotAfter()).append(nl);
    buf.append("            SubjectDN: ").append(this.getSubjectDN()).append(nl);
    buf.append("           Public Key: ").append(this.getPublicKey()).append(nl);
    buf.append("  Signature Algorithm: ").append(this.getSigAlgName()).append(nl);
    byte[] sig = this.getSignature();
    buf.append("            Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
    for (int i = 20; i < sig.length; i += 20) {
        if (i < sig.length - 20) {
            buf.append("                       ").append(new String(Hex.encode(sig, i, 20))).append(nl);
        } else {
            buf.append("                       ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl);
        }
    }
    Extensions extensions = c.getTBSCertificate().getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("       Extensions: \n");
        }
        while (e.hasMoreElements()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
            Extension ext = extensions.getExtension(oid);
            if (ext.getExtnValue() != null) {
                byte[] octs = ext.getExtnValue().getOctets();
                ASN1InputStream dIn = new ASN1InputStream(octs);
                buf.append("                       critical(").append(ext.isCritical()).append(") ");
                try {
                    if (oid.equals(Extension.basicConstraints)) {
                        buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl);
                    } else if (oid.equals(Extension.keyUsage)) {
                        buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) {
                        buf.append(new NetscapeCertType((DERBitString) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
                        buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
                        buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append(nl);
                    } else {
                        buf.append(oid.getId());
                        buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                    //buf.append(" value = ").append("*****").append(nl);
                    }
                } catch (Exception ex) {
                    buf.append(oid.getId());
                    //     buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl);
                    buf.append(" value = ").append("*****").append(nl);
                }
            } else {
                buf.append(nl);
            }
        }
    }
    return buf.toString();
}
Also used : VerisignCzagExtension(org.bouncycastle.asn1.misc.VerisignCzagExtension) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) NetscapeRevocationURL(org.bouncycastle.asn1.misc.NetscapeRevocationURL) DERBitString(org.bouncycastle.asn1.DERBitString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1String(org.bouncycastle.asn1.ASN1String) Extensions(org.bouncycastle.asn1.x509.Extensions) CertificateExpiredException(java.security.cert.CertificateExpiredException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) NoSuchProviderException(java.security.NoSuchProviderException) Extension(org.bouncycastle.asn1.x509.Extension) VerisignCzagExtension(org.bouncycastle.asn1.misc.VerisignCzagExtension) DERIA5String(org.bouncycastle.asn1.DERIA5String) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 49 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project felix by apache.

the class CertificateUtil method createSelfSignedCert.

private static X509Certificate createSelfSignedCert(String commonName, KeyPair keypair) throws Exception {
    PublicKey publicKey = keypair.getPublic();
    String keyAlg = DPSigner.getSignatureAlgorithm(publicKey);
    X500Name issuer = new X500Name(commonName);
    BigInteger serial = BigInteger.probablePrime(16, new Random());
    Date notBefore = new Date(System.currentTimeMillis() - 1000);
    Date notAfter = new Date(notBefore.getTime() + 6000);
    SubjectPublicKeyInfo pubKeyInfo;
    try (ASN1InputStream is = new ASN1InputStream(publicKey.getEncoded())) {
        pubKeyInfo = SubjectPublicKeyInfo.getInstance(is.readObject());
    }
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, pubKeyInfo);
    builder.addExtension(new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(false))));
    X509CertificateHolder certHolder = builder.build(new JcaContentSignerBuilder(keyAlg).build(keypair.getPrivate()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) DEROctetString(org.bouncycastle.asn1.DEROctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) DEROctetString(org.bouncycastle.asn1.DEROctetString) Extension(org.bouncycastle.asn1.x509.Extension) Random(java.util.Random) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 50 with Extension

use of com.github.zhenwei.core.asn1.x509.Extension in project nifi by apache.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));
        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Aggregations

IOException (java.io.IOException)133 Extension (org.bouncycastle.asn1.x509.Extension)131 X509Certificate (java.security.cert.X509Certificate)80 ArrayList (java.util.ArrayList)78 Enumeration (java.util.Enumeration)75 Extensions (org.bouncycastle.asn1.x509.Extensions)70 BigInteger (java.math.BigInteger)62 CertPathValidatorException (java.security.cert.CertPathValidatorException)60 DEROctetString (org.bouncycastle.asn1.DEROctetString)59 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)58 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)57 GeneralSecurityException (java.security.GeneralSecurityException)55 List (java.util.List)55 HashSet (java.util.HashSet)54 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)51 CertificateExpiredException (java.security.cert.CertificateExpiredException)47 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)47 CertPathBuilderException (java.security.cert.CertPathBuilderException)45 Set (java.util.Set)45 GeneralName (org.bouncycastle.asn1.x509.GeneralName)44