Search in sources :

Example 11 with Certificate

use of com.android.apksig.internal.x509.Certificate in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method getTrustManager.

/**
 * Get TrustManager for the algorithm. This is mainly used to get the JVM default trust manager
 * and cache all of the root CA.
 *
 * @param algorithm algorithm.
 * @return TrustManager object.
 */
private X509TrustManager getTrustManager(String algorithm) {
    try {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(algorithm);
        factory.init((KeyStore) null);
        X509TrustManager ret = null;
        for (TrustManager tm : factory.getTrustManagers()) {
            // Manager here.
            if (tm instanceof X509TrustManager) {
                ret = (X509TrustManager) tm;
                break;
            }
        }
        if (ret == null) {
            return null;
        }
        synchronized (ROOT_CA_LOCK) {
            // cache root CA certificates for later use.
            if (ROOT_CA.isEmpty()) {
                for (X509Certificate cert : ret.getAcceptedIssuers()) {
                    Certificate bcCert = Certificate.getInstance(cert.getEncoded());
                    ROOT_CA.put(bcCert.getSubject().hashCode(), bcCert);
                }
            }
        }
        return ret;
    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateEncodingException ex) {
        throw new SSLInitializationException(ex.getMessage(), ex);
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) SSLInitializationException(org.apache.http.ssl.SSLInitializationException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 12 with Certificate

use of com.android.apksig.internal.x509.Certificate in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method getPairIssuerSubject.

/**
 * Creates a pair of Issuer and Subject certificates
 *
 * @param bcChain a list of bouncy castle Certificate
 * @return a list of paif of Issuer and Subject certificates
 */
private List<SFPair<Certificate, Certificate>> getPairIssuerSubject(List<Certificate> bcChain) throws CertificateException {
    List<SFPair<Certificate, Certificate>> pairIssuerSubject = new ArrayList<>();
    for (int i = 0, len = bcChain.size(); i < len; ++i) {
        Certificate bcCert = bcChain.get(i);
        if (bcCert.getIssuer().equals(bcCert.getSubject())) {
            // skipping ROOT CA
            continue;
        }
        if (i < len - 1) {
            pairIssuerSubject.add(SFPair.of(bcChain.get(i + 1), bcChain.get(i)));
        } else {
            // no root CA certificate is attached in the certificate chain, so
            // getting one from the root CA from JVM.
            Certificate issuer = ROOT_CA.get(bcCert.getIssuer().hashCode());
            if (issuer == null) {
                throw new CertificateException("Failed to find the root CA.", new SFOCSPException(OCSPErrorCode.NO_ROOTCA_FOUND, "Failed to find the root CA."));
            }
            pairIssuerSubject.add(SFPair.of(issuer, bcChain.get(i)));
        }
    }
    return pairIssuerSubject;
}
Also used : CertificateException(java.security.cert.CertificateException) SFPair(net.snowflake.client.util.SFPair) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 13 with Certificate

use of com.android.apksig.internal.x509.Certificate in project bitbreeds-webrtc by IIlllII.

the class CertUtil method getCertFingerPrint.

/**
 * @param alias alias
 * @param pass password
 * @param storePath path to keystore
 * @return sha-256 string based on cert in keystore
 */
public static String getCertFingerPrint(String storePath, String alias, String pass) {
    try {
        Certificate cert = DTLSUtils.loadCert(storePath, alias, pass);
        byte[] der = cert.getEncoded();
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] dat = md.digest(der);
        String fingerprint = createFingerprintString(dat);
        logger.info("Local cert signature is {} ", fingerprint);
        return fingerprint;
    } catch (Exception e) {
        logger.error("Failed to create cert fingerprint from {}", storePath, e);
        throw new IllegalStateException("Loading certificate failed");
    }
}
Also used : MessageDigest(java.security.MessageDigest) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 14 with Certificate

use of com.android.apksig.internal.x509.Certificate in project apksig by venshine.

the class ApkSigningBlockUtils method generateSignaturesOverData.

/**
 * uses the SignatureAlgorithms in the provided signerConfig to sign the provided data
 *
 * @return list of signature algorithm IDs and their corresponding signatures over the data.
 */
public static List<Pair<Integer, byte[]>> generateSignaturesOverData(SignerConfig signerConfig, byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException {
    List<Pair<Integer, byte[]>> signatures = new ArrayList<>(signerConfig.signatureAlgorithms.size());
    PublicKey publicKey = signerConfig.certificates.get(0).getPublicKey();
    for (SignatureAlgorithm signatureAlgorithm : signerConfig.signatureAlgorithms) {
        Pair<String, ? extends AlgorithmParameterSpec> sigAlgAndParams = signatureAlgorithm.getJcaSignatureAlgorithmAndParams();
        String jcaSignatureAlgorithm = sigAlgAndParams.getFirst();
        AlgorithmParameterSpec jcaSignatureAlgorithmParams = sigAlgAndParams.getSecond();
        byte[] signatureBytes;
        try {
            Signature signature = Signature.getInstance(jcaSignatureAlgorithm);
            signature.initSign(signerConfig.privateKey);
            if (jcaSignatureAlgorithmParams != null) {
                signature.setParameter(jcaSignatureAlgorithmParams);
            }
            signature.update(data);
            signatureBytes = signature.sign();
        } catch (InvalidKeyException e) {
            throw new InvalidKeyException("Failed to sign using " + jcaSignatureAlgorithm, e);
        } catch (InvalidAlgorithmParameterException | SignatureException e) {
            throw new SignatureException("Failed to sign using " + jcaSignatureAlgorithm, e);
        }
        try {
            Signature signature = Signature.getInstance(jcaSignatureAlgorithm);
            signature.initVerify(publicKey);
            if (jcaSignatureAlgorithmParams != null) {
                signature.setParameter(jcaSignatureAlgorithmParams);
            }
            signature.update(data);
            if (!signature.verify(signatureBytes)) {
                throw new SignatureException("Failed to verify generated " + jcaSignatureAlgorithm + " signature using public key from certificate");
            }
        } catch (InvalidKeyException e) {
            throw new InvalidKeyException("Failed to verify generated " + jcaSignatureAlgorithm + " signature using" + " public key from certificate", e);
        } catch (InvalidAlgorithmParameterException | SignatureException e) {
            throw new SignatureException("Failed to verify generated " + jcaSignatureAlgorithm + " signature using" + " public key from certificate", e);
        }
        signatures.add(Pair.of(signatureAlgorithm.getId(), signatureBytes));
    }
    return signatures;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) RSAPublicKey(com.android.apksig.internal.x509.RSAPublicKey) PublicKey(java.security.PublicKey) ArrayList(java.util.ArrayList) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) Pair(com.android.apksig.internal.util.Pair)

Example 15 with Certificate

use of com.android.apksig.internal.x509.Certificate in project apksig by venshine.

the class X509CertificateUtils method generateCertificates.

/**
 * Generates a {@code Collection} of {@code Certificate} objects from the encoded {@code
 * InputStream} using the provided {@code CertificateFactory}.
 *
 * @throws CertificateException if the InputStream cannot be decoded to zero or more valid
 *                              {@code Certificates} objects.
 */
public static Collection<? extends java.security.cert.Certificate> generateCertificates(InputStream in, CertificateFactory certFactory) throws CertificateException {
    // Since the InputStream is not guaranteed to support mark / reset operations first read it
    // into a byte array to allow using the BER parser / DER encoder if it cannot be read by
    // the CertificateFactory.
    byte[] encodedCerts;
    try {
        encodedCerts = ByteStreams.toByteArray(in);
    } catch (IOException e) {
        throw new CertificateException("Failed to read the input stream", e);
    }
    try {
        return certFactory.generateCertificates(new ByteArrayInputStream(encodedCerts));
    } catch (CertificateException e) {
    // This could be expected if the certificates are encoded using a BER encoding that does
    // not use the minimum number of bytes to represent the length of the contents; attempt
    // to decode the certificates using the BER parser and re-encode using the DER encoder
    // below.
    }
    try {
        Collection<X509Certificate> certificates = new ArrayList<>(1);
        ByteBuffer encodedCertsBuffer = ByteBuffer.wrap(encodedCerts);
        while (encodedCertsBuffer.hasRemaining()) {
            ByteBuffer certBuffer = getNextDEREncodedCertificateBlock(encodedCertsBuffer);
            int startingPos = certBuffer.position();
            Certificate reencodedCert = Asn1BerParser.parse(certBuffer, Certificate.class);
            byte[] reencodedForm = Asn1DerEncoder.encode(reencodedCert);
            X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(reencodedForm));
            byte[] originalEncoding = new byte[certBuffer.position() - startingPos];
            certBuffer.position(startingPos);
            certBuffer.get(originalEncoding);
            GuaranteedEncodedFormX509Certificate guaranteedEncodedCert = new GuaranteedEncodedFormX509Certificate(certificate, originalEncoding);
            certificates.add(guaranteedEncodedCert);
        }
        return certificates;
    } catch (Asn1DecodingException | Asn1EncodingException e) {
        throw new CertificateException("Failed to parse certificates", e);
    }
}
Also used : Asn1EncodingException(com.android.apksig.internal.asn1.Asn1EncodingException) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Asn1DecodingException(com.android.apksig.internal.asn1.Asn1DecodingException) X509Certificate(java.security.cert.X509Certificate) Certificate(com.android.apksig.internal.x509.Certificate)

Aggregations

Certificate (org.bouncycastle.asn1.x509.Certificate)53 IOException (java.io.IOException)40 X509Certificate (java.security.cert.X509Certificate)37 CertificateException (java.security.cert.CertificateException)27 File (java.io.File)12 Test (org.junit.Test)11 BigInteger (java.math.BigInteger)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)9 Test (org.junit.jupiter.api.Test)9 Certificate (com.google.cloud.security.privateca.v1.Certificate)8 CertificateAuthorityServiceClient (com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient)8 SQLException (java.sql.SQLException)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 Certificate (com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)6 Extension (org.bouncycastle.asn1.x509.Extension)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 ArrayList (java.util.ArrayList)5