Search in sources :

Example 61 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project oxAuth by GluuFederation.

the class CRLCertificateVerifier method getCrlNumber.

@SuppressWarnings({ "deprecation", "resource" })
private BigInteger getCrlNumber(X509CRL crl) throws IOException {
    byte[] crlNumberExtensionValue = crl.getExtensionValue(X509Extensions.CRLNumber.getId());
    if (crlNumberExtensionValue == null) {
        return null;
    }
    ASN1OctetString octetString = (ASN1OctetString) (new ASN1InputStream(new ByteArrayInputStream(crlNumberExtensionValue)).readObject());
    byte[] octets = octetString.getOctets();
    ASN1Integer integer = (ASN1Integer) new ASN1InputStream(octets).readObject();
    BigInteger crlNumber = integer.getPositiveValue();
    return crlNumber;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) ASN1Integer(org.bouncycastle.asn1.ASN1Integer)

Example 62 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project zm-mailbox by Zimbra.

the class DataSignerTest method testSignData.

@Test
public void testSignData() {
    try {
        String serverdir = MailboxTestUtil.getZimbraServerDir("");
        FileInputStream p12Stream = new FileInputStream(serverdir + "data/unittest/certificate/sign1_digitalid.p12");
        char[] expPass = "test123export".toCharArray();
        byte[] certBytes = ByteStreams.toByteArray(p12Stream);
        byte[] signedData = DataSigner.signData("hello world".getBytes(), certBytes, expPass);
        // validate signed data
        ByteArrayInputStream inputStream = new ByteArrayInputStream(signedData);
        try (ASN1InputStream asnInputStream = new ASN1InputStream(inputStream)) {
            CMSSignedData cmsSignedData = new CMSSignedData(ContentInfo.getInstance(asnInputStream.readObject()));
            Store certs = cmsSignedData.getCertificates();
            SignerInformationStore signers = cmsSignedData.getSignerInfos();
            Collection<SignerInformation> c = signers.getSigners();
            Iterator<SignerInformation> it = c.iterator();
            SignerInformation signer = it.next();
            Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
            X509CertificateHolder certHolder = certCollection.iterator().next();
            boolean verify = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
            Assert.assertTrue(verify);
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("data sign test failed");
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Store(org.bouncycastle.util.Store) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) Test(org.junit.Test)

Example 63 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project Resurrection_packages_apps_Settings by ResurrectionRemix.

the class CredentialStorage method isHardwareBackedKey.

private boolean isHardwareBackedKey(byte[] keyData) {
    try {
        final ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
        final PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        final String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();
        final String algName = new AlgorithmId(new ObjectIdentifier(algOid)).getName();
        return KeyChain.isBoundKeyAlgorithm(algName);
    } catch (IOException e) {
        Log.e(TAG, "Failed to parse key data");
        return false;
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) AlgorithmId(sun.security.x509.AlgorithmId) IOException(java.io.IOException) PrivateKeyInfo(com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 64 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project ddf by codice.

the class KeystoreEditor method addToStore.

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException {
    OutputStream fos = null;
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException(NULL_ALIAS_MSG);
        }
        Path storeFile = Paths.get(path);
        // check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            // priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            // java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();
            // we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();
                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
        // need to parse der separately from pem, der has the same mime type but is binary hence
        // checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
            Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
        // if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            // This is the catch all case for PEM, P7B, etc. with common file extensions if the mime
            // type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }
                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, "BC");
                    Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.info("Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.info("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}
Also used : OriginatorInfo(org.bouncycastle.asn1.cms.OriginatorInfo) PrivateKey(java.security.PrivateKey) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) X500Name(org.bouncycastle.asn1.x500.X500Name) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) CertificateFactory(java.security.cert.CertificateFactory) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) PEMParser(org.bouncycastle.openssl.PEMParser) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) RDN(org.bouncycastle.asn1.x500.RDN) Path(java.nio.file.Path) PKCS8Key(org.apache.commons.ssl.PKCS8Key) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) Enumeration(java.util.Enumeration) InputStreamReader(java.io.InputStreamReader) SignedData(org.bouncycastle.asn1.cms.SignedData) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) KeyManagementException(java.security.KeyManagementException) MalformedObjectNameException(javax.management.MalformedObjectNameException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) ASN1Set(org.bouncycastle.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BufferedReader(java.io.BufferedReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) Key(java.security.Key) PrivateKey(java.security.PrivateKey) PKCS8Key(org.apache.commons.ssl.PKCS8Key) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 65 with ASN1InputStream

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

the class X509NameEntryConverter method convertHexEncoded.

/**
     * Convert an inline encoded hex string rendition of an ASN.1
     * object back into its corresponding ASN.1 object.
     * 
     * @param str the hex encoded object
     * @param off the index at which the encoding starts
     * @return the decoded object
     */
protected ASN1Primitive convertHexEncoded(String str, int off) throws IOException {
    str = Strings.toLowerCase(str);
    byte[] data = new byte[(str.length() - off) / 2];
    for (int index = 0; index != data.length; index++) {
        char left = str.charAt((index * 2) + off);
        char right = str.charAt((index * 2) + off + 1);
        if (left < 'a') {
            data[index] = (byte) ((left - '0') << 4);
        } else {
            data[index] = (byte) ((left - 'a' + 10) << 4);
        }
        if (right < 'a') {
            data[index] |= (byte) (right - '0');
        } else {
            data[index] |= (byte) (right - 'a' + 10);
        }
    }
    ASN1InputStream aIn = new ASN1InputStream(data);
    return aIn.readObject();
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream)

Aggregations

ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)108 IOException (java.io.IOException)90 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)36 ByteArrayInputStream (java.io.ByteArrayInputStream)35 X509Certificate (java.security.cert.X509Certificate)25 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)25 BigInteger (java.math.BigInteger)21 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)20 CertificateException (java.security.cert.CertificateException)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18 CertificateParsingException (java.security.cert.CertificateParsingException)18 Enumeration (java.util.Enumeration)17 CertificateEncodingException (java.security.cert.CertificateEncodingException)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 InvalidKeyException (java.security.InvalidKeyException)14 CRLException (java.security.cert.CRLException)14 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)12 NoSuchProviderException (java.security.NoSuchProviderException)11