Search in sources :

Example 46 with ASN1Sequence

use of com.android.org.bouncycastle.asn1.ASN1Sequence in project spring-security-oauth by spring-projects.

the class RsaKeyHelper method parseKeyPair.

static KeyPair parseKeyPair(String pemData) {
    Matcher m = PEM_DATA.matcher(pemData.trim());
    if (!m.matches()) {
        throw new IllegalArgumentException("String is not PEM encoded data");
    }
    String type = m.group(1);
    final byte[] content = b64Decode(utf8Encode(m.group(2)));
    PublicKey publicKey;
    PrivateKey privateKey = null;
    try {
        KeyFactory fact = KeyFactory.getInstance("RSA");
        if (type.equals("RSA PRIVATE KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            if (seq.size() != 9) {
                throw new IllegalArgumentException("Invalid RSA Private Key ASN1 sequence.");
            }
            org.bouncycastle.asn1.pkcs.RSAPrivateKey key = org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(key.getModulus(), key.getPublicExponent(), key.getPrivateExponent(), key.getPrime1(), key.getPrime2(), key.getExponent1(), key.getExponent2(), key.getCoefficient());
            publicKey = fact.generatePublic(pubSpec);
            privateKey = fact.generatePrivate(privSpec);
        } else if (type.equals("PUBLIC KEY")) {
            KeySpec keySpec = new X509EncodedKeySpec(content);
            publicKey = fact.generatePublic(keySpec);
        } else if (type.equals("RSA PUBLIC KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            org.bouncycastle.asn1.pkcs.RSAPublicKey key = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            publicKey = fact.generatePublic(pubSpec);
        } else {
            throw new IllegalArgumentException(type + " is not a supported format");
        }
        return new KeyPair(publicKey, privateKey);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
Also used : Matcher(java.util.regex.Matcher) RSAPublicKey(java.security.interfaces.RSAPublicKey) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence)

Example 47 with ASN1Sequence

use of com.android.org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method prepareCertB.

protected static PKIXPolicyNode prepareCertB(CertPath certPath, int index, List[] policyNodes, PKIXPolicyNode validPolicyTree, int policyMapping) 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;
    // (b)
    //
    ASN1Sequence pm = null;
    try {
        pm = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.POLICY_MAPPINGS));
    } catch (AnnotatedException ex) {
        throw new ExtCertPathValidatorException("Policy mappings extension could not be decoded.", ex, certPath, index);
    }
    PKIXPolicyNode _validPolicyTree = validPolicyTree;
    if (pm != null) {
        ASN1Sequence mappings = (ASN1Sequence) pm;
        Map m_idp = new HashMap();
        Set s_idp = new HashSet();
        for (int j = 0; j < mappings.size(); j++) {
            ASN1Sequence mapping = (ASN1Sequence) mappings.getObjectAt(j);
            String id_p = ((DERObjectIdentifier) mapping.getObjectAt(0)).getId();
            String sd_p = ((DERObjectIdentifier) mapping.getObjectAt(1)).getId();
            Set tmp;
            if (!m_idp.containsKey(id_p)) {
                tmp = new HashSet();
                tmp.add(sd_p);
                m_idp.put(id_p, tmp);
                s_idp.add(id_p);
            } else {
                tmp = (Set) m_idp.get(id_p);
                tmp.add(sd_p);
            }
        }
        Iterator it_idp = s_idp.iterator();
        while (it_idp.hasNext()) {
            String id_p = (String) it_idp.next();
            //
            if (policyMapping > 0) {
                boolean idp_found = false;
                Iterator nodes_i = policyNodes[i].iterator();
                while (nodes_i.hasNext()) {
                    PKIXPolicyNode node = (PKIXPolicyNode) nodes_i.next();
                    if (node.getValidPolicy().equals(id_p)) {
                        idp_found = true;
                        node.expectedPolicies = (Set) m_idp.get(id_p);
                        break;
                    }
                }
                if (!idp_found) {
                    nodes_i = policyNodes[i].iterator();
                    while (nodes_i.hasNext()) {
                        PKIXPolicyNode node = (PKIXPolicyNode) nodes_i.next();
                        if (RFC3280CertPathUtilities.ANY_POLICY.equals(node.getValidPolicy())) {
                            Set pq = null;
                            ASN1Sequence policies = null;
                            try {
                                policies = (ASN1Sequence) CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
                            } catch (AnnotatedException e) {
                                throw new ExtCertPathValidatorException("Certificate policies extension could not be decoded.", e, certPath, index);
                            }
                            Enumeration e = policies.getObjects();
                            while (e.hasMoreElements()) {
                                PolicyInformation pinfo = null;
                                try {
                                    pinfo = PolicyInformation.getInstance(e.nextElement());
                                } catch (Exception ex) {
                                    throw new CertPathValidatorException("Policy information could not be decoded.", ex, certPath, index);
                                }
                                if (RFC3280CertPathUtilities.ANY_POLICY.equals(pinfo.getPolicyIdentifier().getId())) {
                                    try {
                                        pq = CertPathValidatorUtilities.getQualifierSet(pinfo.getPolicyQualifiers());
                                    } catch (CertPathValidatorException ex) {
                                        throw new ExtCertPathValidatorException("Policy qualifier info set could not be decoded.", ex, certPath, index);
                                    }
                                    break;
                                }
                            }
                            boolean ci = false;
                            if (cert.getCriticalExtensionOIDs() != null) {
                                ci = cert.getCriticalExtensionOIDs().contains(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
                            }
                            PKIXPolicyNode p_node = (PKIXPolicyNode) node.getParent();
                            if (RFC3280CertPathUtilities.ANY_POLICY.equals(p_node.getValidPolicy())) {
                                PKIXPolicyNode c_node = new PKIXPolicyNode(new ArrayList(), i, (Set) m_idp.get(id_p), p_node, pq, id_p, ci);
                                p_node.addChild(c_node);
                                policyNodes[i].add(c_node);
                            }
                            break;
                        }
                    }
                }
            //
            // (2)
            //
            } else if (policyMapping <= 0) {
                Iterator nodes_i = policyNodes[i].iterator();
                while (nodes_i.hasNext()) {
                    PKIXPolicyNode node = (PKIXPolicyNode) nodes_i.next();
                    if (node.getValidPolicy().equals(id_p)) {
                        PKIXPolicyNode p_node = (PKIXPolicyNode) node.getParent();
                        p_node.removeChild(node);
                        nodes_i.remove();
                        for (int k = (i - 1); k >= 0; k--) {
                            List nodes = policyNodes[k];
                            for (int l = 0; l < nodes.size(); l++) {
                                PKIXPolicyNode node2 = (PKIXPolicyNode) nodes.get(l);
                                if (!node2.hasChildren()) {
                                    _validPolicyTree = CertPathValidatorUtilities.removePolicyNode(_validPolicyTree, policyNodes, node2);
                                    if (_validPolicyTree == null) {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return _validPolicyTree;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) 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) 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) 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) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 48 with ASN1Sequence

use of com.android.org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class RFC3280CertPathUtilities method prepareNextCertG.

protected static void prepareNextCertG(CertPath certPath, int index, PKIXNameConstraintValidator nameConstraintValidator) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    //
    // (g) handle the name constraints extension
    //
    NameConstraints nc = null;
    try {
        ASN1Sequence ncSeq = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.NAME_CONSTRAINTS));
        if (ncSeq != null) {
            nc = new NameConstraints(ncSeq);
        }
    } catch (Exception e) {
        throw new ExtCertPathValidatorException("Name constraints extension could not be decoded.", e, certPath, index);
    }
    if (nc != null) {
        //
        // (g) (1) permitted subtrees
        //
        ASN1Sequence permitted = nc.getPermittedSubtrees();
        if (permitted != null) {
            try {
                nameConstraintValidator.intersectPermittedSubtree(permitted);
            } catch (Exception ex) {
                throw new ExtCertPathValidatorException("Permitted subtrees cannot be build from name constraints extension.", ex, certPath, index);
            }
        }
        //
        // (g) (2) excluded subtrees
        //
        ASN1Sequence excluded = nc.getExcludedSubtrees();
        if (excluded != null) {
            Enumeration e = excluded.getObjects();
            try {
                while (e.hasMoreElements()) {
                    GeneralSubtree subtree = GeneralSubtree.getInstance(e.nextElement());
                    nameConstraintValidator.addExcludedSubtree(subtree);
                }
            } catch (Exception ex) {
                throw new ExtCertPathValidatorException("Excluded subtrees cannot be build from name constraints extension.", ex, certPath, index);
            }
        }
    }
}
Also used : NameConstraints(org.bouncycastle.asn1.x509.NameConstraints) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) Enumeration(java.util.Enumeration) List(java.util.List) ArrayList(java.util.ArrayList) GeneralSubtree(org.bouncycastle.asn1.x509.GeneralSubtree) 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)

Example 49 with ASN1Sequence

use of com.android.org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class X509CRLObject method toString.

/**
     * Returns a string representation of this CRL.
     *
     * @return a string representation of this CRL.
     */
public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("              Version: ").append(this.getVersion()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("          This update: ").append(this.getThisUpdate()).append(nl);
    buf.append("          Next update: ").append(this.getNextUpdate()).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);
        }
    }
    X509Extensions extensions = c.getTBSCertList().getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("           Extensions: ").append(nl);
        }
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (ext.getValue() != null) {
                byte[] octs = ext.getValue().getOctets();
                ASN1InputStream dIn = new ASN1InputStream(octs);
                buf.append("                       critical(").append(ext.isCritical()).append(") ");
                try {
                    if (oid.equals(X509Extensions.CRLNumber)) {
                        buf.append(new CRLNumber(DERInteger.getInstance(dIn.readObject()).getPositiveValue())).append(nl);
                    } else if (oid.equals(X509Extensions.DeltaCRLIndicator)) {
                        buf.append("Base CRL: " + new CRLNumber(DERInteger.getInstance(dIn.readObject()).getPositiveValue())).append(nl);
                    } else if (oid.equals(X509Extensions.IssuingDistributionPoint)) {
                        buf.append(new IssuingDistributionPoint((ASN1Sequence) dIn.readObject())).append(nl);
                    } else if (oid.equals(X509Extensions.CRLDistributionPoints)) {
                        buf.append(new CRLDistPoint((ASN1Sequence) dIn.readObject())).append(nl);
                    } else if (oid.equals(X509Extensions.FreshestCRL)) {
                        buf.append(new CRLDistPoint((ASN1Sequence) dIn.readObject())).append(nl);
                    } else {
                        buf.append(oid.getId());
                        buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                    }
                } catch (Exception ex) {
                    buf.append(oid.getId());
                    buf.append(" value = ").append("*****").append(nl);
                }
            } else {
                buf.append(nl);
            }
        }
    }
    Set set = getRevokedCertificates();
    if (set != null) {
        Iterator it = set.iterator();
        while (it.hasNext()) {
            buf.append(it.next());
            buf.append(nl);
        }
    }
    return buf.toString();
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) HashSet(java.util.HashSet) Set(java.util.Set) X509Extension(org.bouncycastle.asn1.x509.X509Extension) CRLNumber(org.bouncycastle.asn1.x509.CRLNumber) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) SignatureException(java.security.SignatureException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CRLException(java.security.cert.CRLException) NoSuchProviderException(java.security.NoSuchProviderException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) Iterator(java.util.Iterator) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 50 with ASN1Sequence

use of com.android.org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class X509V2AttributeCertificate method getAttributes.

public X509Attribute[] getAttributes() {
    ASN1Sequence seq = cert.getAcinfo().getAttributes();
    X509Attribute[] attrs = new X509Attribute[seq.size()];
    for (int i = 0; i != seq.size(); i++) {
        attrs[i] = new X509Attribute((ASN1Encodable) seq.getObjectAt(i));
    }
    return attrs;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable)

Aggregations

ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)57 IOException (java.io.IOException)31 ArrayList (java.util.ArrayList)29 List (java.util.List)26 Enumeration (java.util.Enumeration)23 X509Certificate (java.security.cert.X509Certificate)22 ExtCertPathValidatorException (org.bouncycastle.jce.exception.ExtCertPathValidatorException)20 CertPathValidatorException (java.security.cert.CertPathValidatorException)18 CertificateExpiredException (java.security.cert.CertificateExpiredException)17 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)17 GeneralSecurityException (java.security.GeneralSecurityException)16 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)16 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)16 IssuingDistributionPoint (org.bouncycastle.asn1.x509.IssuingDistributionPoint)16 DERObjectIdentifier (org.bouncycastle.asn1.DERObjectIdentifier)15 CertPathBuilderException (java.security.cert.CertPathBuilderException)14 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)13 Iterator (java.util.Iterator)10 HashSet (java.util.HashSet)9 Set (java.util.Set)9