Search in sources :

Example 36 with AlgorithmIdentifier

use of com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class SubjectPublicKeyInfoTest method test_getPublicKey_WellKnownOid.

public void test_getPublicKey_WellKnownOid() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair pair = kpg.generateKeyPair();
    final RSAPublicKey rsaPubKey = (RSAPublicKey) pair.getPublic();
    /* Do some fancy footwork to get an ASN.1 SubjectPublicKey for RSA */
    final ASN1Sequence rsaPubKeyInfo = new ASN1Sequence(new ASN1Type[] { ASN1Integer.getInstance(), ASN1Integer.getInstance() }) {

        @Override
        protected void getValues(Object object, Object[] values) {
            values[0] = rsaPubKey.getModulus().toByteArray();
            values[1] = rsaPubKey.getPublicExponent().toByteArray();
        }
    };
    /* The algorithm ID for RSA encryption */
    AlgorithmIdentifier algid = new AlgorithmIdentifier("1.2.840.113549.1.1.1");
    SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(algid, rsaPubKeyInfo.encode(null));
    PublicKey pubKey = spki.getPublicKey();
    assertNotNull(pubKey);
    assertTrue(pubKey instanceof RSAPublicKey);
}
Also used : KeyPair(java.security.KeyPair) ASN1Sequence(org.apache.harmony.security.asn1.ASN1Sequence) RSAPublicKey(java.security.interfaces.RSAPublicKey) X509PublicKey(org.apache.harmony.security.x509.X509PublicKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) KeyPairGenerator(java.security.KeyPairGenerator) SubjectPublicKeyInfo(org.apache.harmony.security.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.apache.harmony.security.x509.AlgorithmIdentifier)

Example 37 with AlgorithmIdentifier

use of com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class PKCS12KeyStoreSpi method engineLoad.

public void engineLoad(InputStream stream, char[] password) throws IOException {
    if (// just initialising
    stream == null) {
        return;
    }
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    BufferedInputStream bufIn = new BufferedInputStream(stream);
    bufIn.mark(10);
    int head = bufIn.read();
    if (head != 0x30) {
        throw new IOException("stream does not represent a PKCS12 key store");
    }
    bufIn.reset();
    ASN1InputStream bIn = new ASN1InputStream(bufIn);
    ASN1Sequence obj = (ASN1Sequence) bIn.readObject();
    Pfx bag = Pfx.getInstance(obj);
    ContentInfo info = bag.getAuthSafe();
    Vector chain = new Vector();
    boolean unmarkedKey = false;
    boolean wrongPKCS12Zero = false;
    if (// check the mac code
    bag.getMacData() != null) {
        MacData mData = bag.getMacData();
        DigestInfo dInfo = mData.getMac();
        AlgorithmIdentifier algId = dInfo.getAlgorithmId();
        byte[] salt = mData.getSalt();
        int itCount = mData.getIterationCount().intValue();
        byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
        try {
            byte[] res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, false, data);
            byte[] dig = dInfo.getDigest();
            if (!Arrays.constantTimeAreEqual(res, dig)) {
                if (password.length > 0) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                // Try with incorrect zero length password
                res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, true, data);
                if (!Arrays.constantTimeAreEqual(res, dig)) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                wrongPKCS12Zero = true;
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException("error constructing MAC: " + e.toString());
        }
    }
    keys = new IgnoresCaseHashtable();
    localIds = new Hashtable();
    if (info.getContentType().equals(data)) {
        bIn = new ASN1InputStream(((ASN1OctetString) info.getContent()).getOctets());
        AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(bIn.readObject());
        ContentInfo[] c = authSafe.getContentInfo();
        for (int i = 0; i != c.length; i++) {
            if (c[i].getContentType().equals(data)) {
                ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString) c[i].getContent()).getOctets());
                ASN1Sequence seq = (ASN1Sequence) dIn.readObject();
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
                    if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        if (b.getBagAttributes() != null) {
                            Enumeration e = b.getBagAttributes().getObjects();
                            while (e.hasMoreElements()) {
                                ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                                ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                                ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                                ASN1Primitive attr = null;
                                if (attrSet.size() > 0) {
                                    attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                    ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                    if (existing != null) {
                                        // OK, but the value has to be the same
                                        if (!existing.toASN1Primitive().equals(attr)) {
                                            throw new IOException("attempt to add existing attribute with different value");
                                        }
                                    } else {
                                        bagAttr.setBagAttribute(aOid, attr);
                                    }
                                }
                                if (aOid.equals(pkcs_9_at_friendlyName)) {
                                    alias = ((DERBMPString) attr).getString();
                                    keys.put(alias, privKey);
                                } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                    localId = (ASN1OctetString) attr;
                                }
                            }
                        }
                        if (localId != null) {
                            String name = new String(Hex.encode(localId.getOctets()));
                            if (alias == null) {
                                keys.put(name, privKey);
                            } else {
                                localIds.put(alias, name);
                            }
                        } else {
                            unmarkedKey = true;
                            keys.put("unmarked", privKey);
                        }
                    } else if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else {
                        System.out.println("extra in data " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else if (c[i].getContentType().equals(encryptedData)) {
                EncryptedData d = EncryptedData.getInstance(c[i].getContent());
                byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
                ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(octets);
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
                    if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                            ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            ASN1Primitive attr = null;
                            if (attrSet.size() > 0) {
                                attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.toASN1Primitive().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                            }
                            if (aOid.equals(pkcs_9_at_friendlyName)) {
                                alias = ((DERBMPString) attr).getString();
                                keys.put(alias, privKey);
                            } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                localId = (ASN1OctetString) attr;
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else if (b.getBagId().equals(keyBag)) {
                        org.bouncycastle.asn1.pkcs.PrivateKeyInfo kInfo = org.bouncycastle.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = BouncyCastleProvider.getPrivateKey(kInfo);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                            ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            ASN1Primitive attr = null;
                            if (attrSet.size() > 0) {
                                attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.toASN1Primitive().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                            }
                            if (aOid.equals(pkcs_9_at_friendlyName)) {
                                alias = ((DERBMPString) attr).getString();
                                keys.put(alias, privKey);
                            } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                localId = (ASN1OctetString) attr;
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else {
                        System.out.println("extra in encryptedData " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else {
                System.out.println("extra " + c[i].getContentType().getId());
                System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent()));
            }
        }
    }
    certs = new IgnoresCaseHashtable();
    chainCerts = new Hashtable();
    keyCerts = new Hashtable();
    for (int i = 0; i != chain.size(); i++) {
        SafeBag b = (SafeBag) chain.elementAt(i);
        CertBag cb = CertBag.getInstance(b.getBagValue());
        if (!cb.getCertId().equals(x509Certificate)) {
            throw new RuntimeException("Unsupported certificate type: " + cb.getCertId());
        }
        Certificate cert;
        try {
            ByteArrayInputStream cIn = new ByteArrayInputStream(((ASN1OctetString) cb.getCertValue()).getOctets());
            cert = certFact.generateCertificate(cIn);
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
        //
        // set the attributes
        //
        ASN1OctetString localId = null;
        String alias = null;
        if (b.getBagAttributes() != null) {
            Enumeration e = b.getBagAttributes().getObjects();
            while (e.hasMoreElements()) {
                ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                ASN1Primitive attr = (ASN1Primitive) ((ASN1Set) sq.getObjectAt(1)).getObjectAt(0);
                PKCS12BagAttributeCarrier bagAttr = null;
                if (cert instanceof PKCS12BagAttributeCarrier) {
                    bagAttr = (PKCS12BagAttributeCarrier) cert;
                    ASN1Encodable existing = bagAttr.getBagAttribute(oid);
                    if (existing != null) {
                        // OK, but the value has to be the same
                        if (!existing.toASN1Primitive().equals(attr)) {
                            throw new IOException("attempt to add existing attribute with different value");
                        }
                    } else {
                        bagAttr.setBagAttribute(oid, attr);
                    }
                }
                if (oid.equals(pkcs_9_at_friendlyName)) {
                    alias = ((DERBMPString) attr).getString();
                } else if (oid.equals(pkcs_9_at_localKeyId)) {
                    localId = (ASN1OctetString) attr;
                }
            }
        }
        chainCerts.put(new CertId(cert.getPublicKey()), cert);
        if (unmarkedKey) {
            if (keyCerts.isEmpty()) {
                String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier()));
                keyCerts.put(name, cert);
                keys.put(name, keys.remove("unmarked"));
            }
        } else {
            //
            if (localId != null) {
                String name = new String(Hex.encode(localId.getOctets()));
                keyCerts.put(name, cert);
            }
            if (alias != null) {
                certs.put(alias, cert);
            }
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) AuthenticatedSafe(org.bouncycastle.asn1.pkcs.AuthenticatedSafe) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DEROctetString(org.bouncycastle.asn1.DEROctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) BufferedInputStream(java.io.BufferedInputStream) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) MacData(org.bouncycastle.asn1.pkcs.MacData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Hashtable(java.util.Hashtable) IOException(java.io.IOException) SafeBag(org.bouncycastle.asn1.pkcs.SafeBag) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) CertBag(org.bouncycastle.asn1.pkcs.CertBag) ASN1Set(org.bouncycastle.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 38 with AlgorithmIdentifier

use of com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class PKCS10CertificationRequest method getPublicKey.

public PublicKey getPublicKey(String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    SubjectPublicKeyInfo subjectPKInfo = reqInfo.getSubjectPublicKeyInfo();
    try {
        X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes());
        AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
        try {
            if (provider == null) {
                return KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec);
            } else {
                return KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), provider).generatePublic(xspec);
            }
        } catch (NoSuchAlgorithmException e) {
            //
            if (keyAlgorithms.get(keyAlg.getObjectId()) != null) {
                String keyAlgorithm = (String) keyAlgorithms.get(keyAlg.getObjectId());
                if (provider == null) {
                    return KeyFactory.getInstance(keyAlgorithm).generatePublic(xspec);
                } else {
                    return KeyFactory.getInstance(keyAlgorithm, provider).generatePublic(xspec);
                }
            }
            throw e;
        }
    } catch (InvalidKeySpecException e) {
        throw new InvalidKeyException("error decoding public key");
    } catch (IOException e) {
        throw new InvalidKeyException("error decoding public key");
    }
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) DERBitString(org.bouncycastle.asn1.DERBitString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DERBitString(org.bouncycastle.asn1.DERBitString) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 39 with AlgorithmIdentifier

use of com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class JcaContentVerifierProviderBuilder method build.

public ContentVerifierProvider build(final PublicKey publicKey) throws OperatorCreationException {
    return new ContentVerifierProvider() {

        public boolean hasAssociatedCertificate() {
            return false;
        }

        public X509CertificateHolder getAssociatedCertificate() {
            return null;
        }

        public ContentVerifier get(AlgorithmIdentifier algorithm) throws OperatorCreationException {
            SignatureOutputStream stream = createSignatureStream(algorithm, publicKey);
            Signature rawSig = createRawSig(algorithm, publicKey);
            if (rawSig != null) {
                return new RawSigVerifier(algorithm, stream, rawSig);
            } else {
                return new SigVerifier(algorithm, stream);
            }
        }
    };
}
Also used : Signature(java.security.Signature) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 40 with AlgorithmIdentifier

use of com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class JcaContentVerifierProviderBuilder method build.

public ContentVerifierProvider build(final X509Certificate certificate) throws OperatorCreationException {
    final X509CertificateHolder certHolder;
    try {
        certHolder = new JcaX509CertificateHolder(certificate);
    } catch (CertificateEncodingException e) {
        throw new OperatorCreationException("cannot process certificate: " + e.getMessage(), e);
    }
    return new ContentVerifierProvider() {

        private SignatureOutputStream stream;

        public boolean hasAssociatedCertificate() {
            return true;
        }

        public X509CertificateHolder getAssociatedCertificate() {
            return certHolder;
        }

        public ContentVerifier get(AlgorithmIdentifier algorithm) throws OperatorCreationException {
            try {
                Signature sig = helper.createSignature(algorithm);
                sig.initVerify(certificate.getPublicKey());
                stream = new SignatureOutputStream(sig);
            } catch (GeneralSecurityException e) {
                throw new OperatorCreationException("exception on setup: " + e, e);
            }
            Signature rawSig = createRawSig(algorithm, certificate.getPublicKey());
            if (rawSig != null) {
                return new RawSigVerifier(algorithm, stream, rawSig);
            } else {
                return new SigVerifier(algorithm, stream);
            }
        }
    };
}
Also used : X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) Signature(java.security.Signature) GeneralSecurityException(java.security.GeneralSecurityException) CertificateEncodingException(java.security.cert.CertificateEncodingException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)31 IOException (java.io.IOException)18 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)11 DERObjectIdentifier (org.bouncycastle.asn1.DERObjectIdentifier)11 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)10 X962Parameters (org.bouncycastle.asn1.x9.X962Parameters)10 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)10 BigInteger (java.math.BigInteger)9 X509Certificate (java.security.cert.X509Certificate)8 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 GeneralSecurityException (java.security.GeneralSecurityException)6 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)6 ECNamedCurveSpec (org.bouncycastle.jce.spec.ECNamedCurveSpec)6 ECCurve (org.bouncycastle.math.ec.ECCurve)6 ASN1EncodableVector (com.android.org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)5 ASN1Integer (com.android.org.bouncycastle.asn1.ASN1Integer)5 ASN1ObjectIdentifier (com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)5