Search in sources :

Example 31 with ASN1InputStream

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

the class CredentialStorage method isHardwareBackedKey.

private boolean isHardwareBackedKey(byte[] keyData) {
    try {
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(keyData));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getAlgorithmId().getAlgorithm().getId();
        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 32 with ASN1InputStream

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

the class CertInstallerHelper method isCa.

private boolean isCa(X509Certificate cert) {
    try {
        byte[] asn1EncodedBytes = cert.getExtensionValue("2.5.29.19");
        if (asn1EncodedBytes == null) {
            return false;
        }
        DEROctetString derOctetString = (DEROctetString) new ASN1InputStream(asn1EncodedBytes).readObject();
        byte[] octets = derOctetString.getOctets();
        ASN1Sequence sequence = (ASN1Sequence) new ASN1InputStream(octets).readObject();
        return BasicConstraints.getInstance(sequence).isCA();
    } catch (IOException e) {
        return false;
    }
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ASN1Sequence(com.android.org.bouncycastle.asn1.ASN1Sequence) IOException(java.io.IOException) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString)

Example 33 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project keystore-explorer by kaikramer.

the class X509Ext method getNetscapeCertificateTypeStringValue.

private String getNetscapeCertificateTypeStringValue(byte[] value) throws IOException {
    // @formatter:off
    /*
		 * NetscapeCertType ::= BIT STRING { sslClient (0), sslServer (1), smime
		 * (2), objectSigning (3), reserved (4), sslCA (5), smimeCA (6),
		 * objectSigningCA (7) }
		 */
    // @formatter:on
    StringBuilder sb = new StringBuilder();
    // we have a ByteArrayInputStream here which does not need to be closed
    @SuppressWarnings("resource") DERBitString netscapeCertType = DERBitString.getInstance(new ASN1InputStream(value).readObject());
    int netscapeCertTypes = netscapeCertType.intValue();
    if (isCertType(netscapeCertTypes, NetscapeCertType.sslClient)) {
        sb.append(res.getString("SslClientNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    if (isCertType(netscapeCertTypes, NetscapeCertType.sslServer)) {
        sb.append(res.getString("SslServerNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    if (isCertType(netscapeCertTypes, NetscapeCertType.smime)) {
        sb.append(res.getString("SmimeNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    if (isCertType(netscapeCertTypes, NetscapeCertType.objectSigning)) {
        sb.append(res.getString("ObjectSigningNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    if (isCertType(netscapeCertTypes, NetscapeCertType.reserved)) {
        sb.append(res.getString("ReservedNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    if (isCertType(netscapeCertTypes, NetscapeCertType.sslCA)) {
        sb.append(res.getString("SslCaNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    if (isCertType(netscapeCertTypes, NetscapeCertType.smimeCA)) {
        sb.append(res.getString("SmimeCaNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    if (isCertType(netscapeCertTypes, NetscapeCertType.objectSigningCA)) {
        sb.append(res.getString("ObjectSigningCaNetscapeCertificateType"));
        sb.append(NEWLINE);
    }
    return sb.toString();
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) DERBitString(org.bouncycastle.asn1.DERBitString) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint)

Example 34 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project keystore-explorer by kaikramer.

the class OpenSslPvkUtil method load.

/**
 * Load an unencrypted OpenSSL private key from the stream. The encoding of
 * the private key may be PEM or DER.
 *
 * @param is
 *            Stream to load the unencrypted private key from
 * @return The private key
 * @throws PrivateKeyEncryptedException
 *             If private key is encrypted
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             An I/O error occurred
 */
public static PrivateKey load(InputStream is) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));
    if (encType == null) {
        throw new CryptoException(res.getString("NotValidOpenSsl.exception.message"));
    }
    if (encType == ENCRYPTED) {
        throw new PrivateKeyEncryptedException(res.getString("OpenSslIsEncrypted.exception.message"));
    }
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));
    if (pemInfo != null) {
        // It is - get DER from PEM
        streamContents = pemInfo.getContent();
    }
    try {
        // Read OpenSSL DER structure
        ASN1InputStream asn1InputStream = new ASN1InputStream(streamContents);
        ASN1Primitive openSsl = asn1InputStream.readObject();
        asn1InputStream.close();
        if (openSsl instanceof ASN1Sequence) {
            ASN1Sequence seq = (ASN1Sequence) openSsl;
            if (seq.size() == 9) {
                // RSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger modulus = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger publicExponent = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger privateExponent = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                BigInteger primeP = ((ASN1Integer) seq.getObjectAt(4)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                BigInteger primeExponentP = ((ASN1Integer) seq.getObjectAt(6)).getValue();
                BigInteger primeExponenetQ = ((ASN1Integer) seq.getObjectAt(7)).getValue();
                BigInteger crtCoefficient = ((ASN1Integer) seq.getObjectAt(8)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, primeExponenetQ, crtCoefficient);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                return keyFactory.generatePrivate(rsaPrivateCrtKeySpec);
            } else if (seq.size() == 6) {
                // DSA private key
                BigInteger version = ((ASN1Integer) seq.getObjectAt(0)).getValue();
                BigInteger primeModulusP = ((ASN1Integer) seq.getObjectAt(1)).getValue();
                BigInteger primeQ = ((ASN1Integer) seq.getObjectAt(2)).getValue();
                BigInteger generatorG = ((ASN1Integer) seq.getObjectAt(3)).getValue();
                // publicExponentY not req for pvk: sequence.getObjectAt(4);
                BigInteger secretExponentX = ((ASN1Integer) seq.getObjectAt(5)).getValue();
                if (!version.equals(VERSION)) {
                    throw new CryptoException(MessageFormat.format(res.getString("OpenSslVersionIncorrect.exception.message"), "" + VERSION.intValue(), "" + version.intValue()));
                }
                DSAPrivateKeySpec dsaPrivateKeySpec = new DSAPrivateKeySpec(secretExponentX, primeModulusP, primeQ, generatorG);
                KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                return keyFactory.generatePrivate(dsaPrivateKeySpec);
            } else if (seq.size() >= 2) {
                // EC private key (RFC 5915)
                org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
                AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
                PrivateKeyInfo privInfo = new PrivateKeyInfo(algId, pKey);
                return new JcaPEMKeyConverter().getPrivateKey(privInfo);
            } else {
                throw new CryptoException(MessageFormat.format(res.getString("OpenSslSequenceIncorrectSize.exception.message"), "" + seq.size()));
            }
        } else {
            throw new CryptoException(res.getString("OpenSslSequenceNotFound.exception.message"));
        }
    } catch (Exception ex) {
        throw new CryptoException(res.getString("NoLoadOpenSslPrivateKey.exception.message"), ex);
    }
}
Also used : RSAPrivateCrtKeySpec(java.security.spec.RSAPrivateCrtKeySpec) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) PemInfo(org.kse.utilities.pem.PemInfo) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CryptoException(org.kse.crypto.CryptoException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) CryptoException(org.kse.crypto.CryptoException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) KeyFactory(java.security.KeyFactory) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 35 with ASN1InputStream

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

the class DefaultTimeStampVerificationProvider method verifyToken.

@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput) throws TimeStampTokenVerificationException {
    TimeStampToken tsToken;
    try {
        ASN1InputStream asn1is = new ASN1InputStream(timeStampToken);
        ContentInfo tsContentInfo = ContentInfo.getInstance(asn1is.readObject());
        asn1is.close();
        tsToken = new TimeStampToken(tsContentInfo);
    } catch (IOException ex) {
        throw new TimeStampTokenStructureException("Error parsing encoded token", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenStructureException("Invalid token", ex);
    }
    X509Certificate tsaCert = null;
    try {
        /* Validate the TSA certificate */
        LinkedList<X509Certificate> certs = new LinkedList<X509Certificate>();
        for (Object certHolder : tsToken.getCertificates().getMatches(new AllCertificatesSelector())) {
            certs.add(this.x509CertificateConverter.getCertificate((X509CertificateHolder) certHolder));
        }
        ValidationData vData = this.certificateValidationProvider.validate(x509CertSelectorConverter.getCertSelector(tsToken.getSID()), tsToken.getTimeStampInfo().getGenTime(), certs);
        tsaCert = vData.getCerts().get(0);
    } catch (CertificateException ex) {
        throw new TimeStampTokenVerificationException(ex.getMessage(), ex);
    } catch (XAdES4jException ex) {
        throw new TimeStampTokenTSACertException("cannot validate TSA certificate", ex);
    }
    try {
        tsToken.validate(this.signerInfoVerifierBuilder.build(tsaCert));
    } catch (TSPValidationException ex) {
        throw new TimeStampTokenSignatureException("Invalid token signature or certificate", ex);
    } catch (Exception ex) {
        throw new TimeStampTokenVerificationException("Error when verifying the token signature", ex);
    }
    org.bouncycastle.tsp.TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo();
    try {
        String digestAlgUri = uriForDigest(tsTokenInfo.getMessageImprintAlgOID());
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        if (!Arrays.equals(md.digest(tsDigestInput), tsTokenInfo.getMessageImprintDigest())) {
            throw new TimeStampTokenDigestException();
        }
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenVerificationException("The token's digest algorithm is not supported", ex);
    }
    return tsTokenInfo.getGenTime();
}
Also used : CertificateException(java.security.cert.CertificateException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) MessageDigest(java.security.MessageDigest) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ValidationData(xades4j.providers.ValidationData) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken)

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