Search in sources :

Example 26 with X509Certificate

use of java.security.cert.X509Certificate in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStore method setPrivateKeyEntry.

private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain, KeyStoreParameter params) throws KeyStoreException {
    byte[] keyBytes = null;
    final String pkeyAlias;
    if (key instanceof OpenSSLKeyHolder) {
        pkeyAlias = ((OpenSSLKeyHolder) key).getOpenSSLKey().getAlias();
    } else {
        pkeyAlias = null;
    }
    final boolean shouldReplacePrivateKey;
    if (pkeyAlias != null && pkeyAlias.startsWith(Credentials.USER_PRIVATE_KEY)) {
        final String keySubalias = pkeyAlias.substring(Credentials.USER_PRIVATE_KEY.length());
        if (!alias.equals(keySubalias)) {
            throw new KeyStoreException("Can only replace keys with same alias: " + alias + " != " + keySubalias);
        }
        shouldReplacePrivateKey = false;
    } else {
        // Make sure the PrivateKey format is the one we support.
        final String keyFormat = key.getFormat();
        if ((keyFormat == null) || (!"PKCS#8".equals(keyFormat))) {
            throw new KeyStoreException("Only PrivateKeys that can be encoded into PKCS#8 are supported");
        }
        // Make sure we can actually encode the key.
        keyBytes = key.getEncoded();
        if (keyBytes == null) {
            throw new KeyStoreException("PrivateKey has no encoding");
        }
        shouldReplacePrivateKey = true;
    }
    // Make sure the chain exists since this is a PrivateKey
    if ((chain == null) || (chain.length == 0)) {
        throw new KeyStoreException("Must supply at least one Certificate with PrivateKey");
    }
    // Do chain type checking.
    X509Certificate[] x509chain = new X509Certificate[chain.length];
    for (int i = 0; i < chain.length; i++) {
        if (!"X.509".equals(chain[i].getType())) {
            throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
        }
        if (!(chain[i] instanceof X509Certificate)) {
            throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" + i);
        }
        x509chain[i] = (X509Certificate) chain[i];
    }
    final byte[] userCertBytes;
    try {
        userCertBytes = x509chain[0].getEncoded();
    } catch (CertificateEncodingException e) {
        throw new KeyStoreException("Couldn't encode certificate #1", e);
    }
    /*
         * If we have a chain, store it in the CA certificate slot for this
         * alias as concatenated DER-encoded certificates. These can be
         * deserialized by {@link CertificateFactory#generateCertificates}.
         */
    final byte[] chainBytes;
    if (chain.length > 1) {
        /*
             * The chain is passed in as {user_cert, ca_cert_1, ca_cert_2, ...}
             * so we only need the certificates starting at index 1.
             */
        final byte[][] certsBytes = new byte[x509chain.length - 1][];
        int totalCertLength = 0;
        for (int i = 0; i < certsBytes.length; i++) {
            try {
                certsBytes[i] = x509chain[i + 1].getEncoded();
                totalCertLength += certsBytes[i].length;
            } catch (CertificateEncodingException e) {
                throw new KeyStoreException("Can't encode Certificate #" + i, e);
            }
        }
        /*
             * Serialize this into one byte array so we can later call
             * CertificateFactory#generateCertificates to recover them.
             */
        chainBytes = new byte[totalCertLength];
        int outputOffset = 0;
        for (int i = 0; i < certsBytes.length; i++) {
            final int certLength = certsBytes[i].length;
            System.arraycopy(certsBytes[i], 0, chainBytes, outputOffset, certLength);
            outputOffset += certLength;
            certsBytes[i] = null;
        }
    } else {
        chainBytes = null;
    }
    /*
         * Make sure we clear out all the appropriate types before trying to
         * write.
         */
    if (shouldReplacePrivateKey) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
    } else {
        Credentials.deleteCertificateTypesForAlias(mKeyStore, alias);
    }
    final int flags = (params == null) ? 0 : params.getFlags();
    if (shouldReplacePrivateKey && !mKeyStore.importKey(Credentials.USER_PRIVATE_KEY + alias, keyBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put private key in keystore");
    } else if (!mKeyStore.put(Credentials.USER_CERTIFICATE + alias, userCertBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put certificate #1 in keystore");
    } else if (chainBytes != null && !mKeyStore.put(Credentials.CA_CERTIFICATE + alias, chainBytes, android.security.KeyStore.UID_SELF, flags)) {
        Credentials.deleteAllTypesForAlias(mKeyStore, alias);
        throw new KeyStoreException("Couldn't put certificate chain in keystore");
    }
}
Also used : OpenSSLKeyHolder(org.apache.harmony.xnet.provider.jsse.OpenSSLKeyHolder) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate)

Example 27 with X509Certificate

use of java.security.cert.X509Certificate in project android_frameworks_base by ParanoidAndroid.

the class Credentials method convertFromPem.

/**
     * Convert objects from PEM format, which is used for
     * CA_CERTIFICATE and USER_CERTIFICATE entries.
     */
public static List<X509Certificate> convertFromPem(byte[] bytes) throws IOException, CertificateException {
    ByteArrayInputStream bai = new ByteArrayInputStream(bytes);
    Reader reader = new InputStreamReader(bai, Charsets.US_ASCII);
    PemReader pr = new PemReader(reader);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> result = new ArrayList<X509Certificate>();
    PemObject o;
    while ((o = pr.readPemObject()) != null) {
        if (o.getType().equals("CERTIFICATE")) {
            Certificate c = cf.generateCertificate(new ByteArrayInputStream(o.getContent()));
            result.add((X509Certificate) c);
        } else {
            throw new IllegalArgumentException("Unknown type " + o.getType());
        }
    }
    pr.close();
    return result;
}
Also used : PemReader(com.android.org.bouncycastle.util.io.pem.PemReader) PemObject(com.android.org.bouncycastle.util.io.pem.PemObject) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) ArrayList(java.util.ArrayList) Reader(java.io.Reader) PemReader(com.android.org.bouncycastle.util.io.pem.PemReader) InputStreamReader(java.io.InputStreamReader) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 28 with X509Certificate

use of java.security.cert.X509Certificate in project Anki-Android by Ramblurr.

the class EasyX509TrustManager method checkServerTrusted.

/**
     * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
     */
@Override
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    // Clean up the certificates chain and build a new one.
    // Theoretically, we shouldn't have to do this, but various web servers
    // in practice are mis-configured to have out-of-order certificates or
    // expired self-issued root certificate.
    int chainLength = certificates.length;
    if (certificates.length > 1) {
        // 1. we clean the received certificates chain.
        // We start from the end-entity certificate, tracing down by matching
        // the "issuer" field and "subject" field until we can't continue.
        // This helps when the certificates are out of order or
        // some certificates are not related to the site.
        int currIndex;
        for (currIndex = 0; currIndex < certificates.length; ++currIndex) {
            boolean foundNext = false;
            for (int nextIndex = currIndex + 1; nextIndex < certificates.length; ++nextIndex) {
                if (certificates[currIndex].getIssuerDN().equals(certificates[nextIndex].getSubjectDN())) {
                    foundNext = true;
                    // Exchange certificates so that 0 through currIndex + 1 are in proper order
                    if (nextIndex != currIndex + 1) {
                        X509Certificate tempCertificate = certificates[nextIndex];
                        certificates[nextIndex] = certificates[currIndex + 1];
                        certificates[currIndex + 1] = tempCertificate;
                    }
                    break;
                }
            }
            if (!foundNext) {
                break;
            }
        }
        // 2. we exam if the last traced certificate is self issued and it is expired.
        // If so, we drop it and pass the rest to checkServerTrusted(), hoping we might
        // have a similar but unexpired trusted root.
        chainLength = currIndex + 1;
        X509Certificate lastCertificate = certificates[chainLength - 1];
        Date now = new Date();
        if (lastCertificate.getSubjectDN().equals(lastCertificate.getIssuerDN()) && now.after(lastCertificate.getNotAfter())) {
            --chainLength;
        }
    }
    standardTrustManager.checkServerTrusted(certificates, authType);
}
Also used : X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date)

Example 29 with X509Certificate

use of java.security.cert.X509Certificate in project walle by Meituan-Dianping.

the class V2SchemeVerifier method parseSigner.

/**
     * Parses the provided signer block and populates the {@code result}.
     *
     * <p>This verifies signatures over {@code signed-data} contained in this block but does not
     * verify the integrity of the rest of the APK. Rather, this method adds to the
     * {@code contentDigestsToVerify}.
     */
private static void parseSigner(ByteBuffer signerBlock, CertificateFactory certFactory, Result.SignerInfo result, Set<ContentDigestAlgorithm> contentDigestsToVerify) throws IOException {
    ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
    byte[] signedDataBytes = new byte[signedData.remaining()];
    signedData.get(signedDataBytes);
    signedData.flip();
    result.signedData = signedDataBytes;
    ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
    byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
    // Parse the signatures block and identify supported signatures
    int signatureCount = 0;
    List<SupportedSignature> supportedSignatures = new ArrayList<>(1);
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            int sigAlgorithmId = signature.getInt();
            byte[] sigBytes = readLengthPrefixedByteArray(signature);
            result.signatures.add(new Result.SignerInfo.Signature(sigAlgorithmId, sigBytes));
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(sigAlgorithmId);
            if (signatureAlgorithm == null) {
                result.addWarning(Issue.V2_SIG_UNKNOWN_SIG_ALGORITHM, sigAlgorithmId);
                continue;
            }
            supportedSignatures.add(new SupportedSignature(signatureAlgorithm, sigBytes));
        } catch (IOException | BufferUnderflowException e) {
            result.addError(Issue.V2_SIG_MALFORMED_SIGNATURE, signatureCount);
            return;
        }
    }
    if (result.signatures.isEmpty()) {
        result.addError(Issue.V2_SIG_NO_SIGNATURES);
        return;
    }
    // Verify signatures over signed-data block using the public key
    List<SupportedSignature> signaturesToVerify = getSignaturesToVerify(supportedSignatures);
    if (signaturesToVerify.isEmpty()) {
        result.addError(Issue.V2_SIG_NO_SUPPORTED_SIGNATURES);
        return;
    }
    for (SupportedSignature signature : signaturesToVerify) {
        SignatureAlgorithm signatureAlgorithm = signature.algorithm;
        String jcaSignatureAlgorithm = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getFirst();
        AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getSecond();
        String keyAlgorithm = signatureAlgorithm.getJcaKeyAlgorithm();
        PublicKey publicKey;
        try {
            publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        } catch (Exception e) {
            result.addError(Issue.V2_SIG_MALFORMED_PUBLIC_KEY, e);
            return;
        }
        try {
            Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
            sig.initVerify(publicKey);
            if (jcaSignatureAlgorithmParams != null) {
                sig.setParameter(jcaSignatureAlgorithmParams);
            }
            signedData.position(0);
            sig.update(signedData);
            byte[] sigBytes = signature.signature;
            if (!sig.verify(sigBytes)) {
                result.addError(Issue.V2_SIG_DID_NOT_VERIFY, signatureAlgorithm);
                return;
            }
            result.verifiedSignatures.put(signatureAlgorithm, sigBytes);
            contentDigestsToVerify.add(signatureAlgorithm.getContentDigestAlgorithm());
        } catch (Exception e) {
            result.addError(Issue.V2_SIG_VERIFY_EXCEPTION, signatureAlgorithm, e);
            return;
        }
    }
    // At least one signature over signedData has verified. We can now parse signed-data.
    signedData.position(0);
    ByteBuffer digests = getLengthPrefixedSlice(signedData);
    ByteBuffer certificates = getLengthPrefixedSlice(signedData);
    ByteBuffer additionalAttributes = getLengthPrefixedSlice(signedData);
    // Parse the certificates block
    int certificateIndex = -1;
    while (certificates.hasRemaining()) {
        certificateIndex++;
        byte[] encodedCert = readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            result.addError(Issue.V2_SIG_MALFORMED_CERTIFICATE, certificateIndex, certificateIndex + 1, e);
            return;
        }
        // Wrap the cert so that the result's getEncoded returns exactly the original encoded
        // form. Without this, getEncoded may return a different form from what was stored in
        // the signature. This is becase some X509Certificate(Factory) implementations re-encode
        // certificates.
        certificate = new GuaranteedEncodedFormX509Certificate(certificate, encodedCert);
        result.certs.add(certificate);
    }
    if (result.certs.isEmpty()) {
        result.addError(Issue.V2_SIG_NO_CERTIFICATES);
        return;
    }
    X509Certificate mainCertificate = result.certs.get(0);
    byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
    if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
        result.addError(Issue.V2_SIG_PUBLIC_KEY_MISMATCH_BETWEEN_CERTIFICATE_AND_SIGNATURES_RECORD, toHex(certificatePublicKeyBytes), toHex(publicKeyBytes));
        return;
    }
    // Parse the digests block
    int digestCount = 0;
    while (digests.hasRemaining()) {
        digestCount++;
        try {
            ByteBuffer digest = getLengthPrefixedSlice(digests);
            int sigAlgorithmId = digest.getInt();
            byte[] digestBytes = readLengthPrefixedByteArray(digest);
            result.contentDigests.add(new Result.SignerInfo.ContentDigest(sigAlgorithmId, digestBytes));
        } catch (IOException | BufferUnderflowException e) {
            result.addError(Issue.V2_SIG_MALFORMED_DIGEST, digestCount);
            return;
        }
    }
    List<Integer> sigAlgsFromSignaturesRecord = new ArrayList<>(result.signatures.size());
    for (Result.SignerInfo.Signature signature : result.signatures) {
        sigAlgsFromSignaturesRecord.add(signature.getAlgorithmId());
    }
    List<Integer> sigAlgsFromDigestsRecord = new ArrayList<>(result.contentDigests.size());
    for (Result.SignerInfo.ContentDigest digest : result.contentDigests) {
        sigAlgsFromDigestsRecord.add(digest.getSignatureAlgorithmId());
    }
    if (!sigAlgsFromSignaturesRecord.equals(sigAlgsFromDigestsRecord)) {
        result.addError(Issue.V2_SIG_SIG_ALG_MISMATCH_BETWEEN_SIGNATURES_AND_DIGESTS_RECORDS, sigAlgsFromSignaturesRecord, sigAlgsFromDigestsRecord);
        return;
    }
    // Parse the additional attributes block.
    int additionalAttributeCount = 0;
    while (additionalAttributes.hasRemaining()) {
        additionalAttributeCount++;
        try {
            ByteBuffer attribute = getLengthPrefixedSlice(additionalAttributes);
            int id = attribute.getInt();
            byte[] value = readLengthPrefixedByteArray(attribute);
            result.additionalAttributes.add(new Result.SignerInfo.AdditionalAttribute(id, value));
            result.addWarning(Issue.V2_SIG_UNKNOWN_ADDITIONAL_ATTRIBUTE, id);
        } catch (IOException | BufferUnderflowException e) {
            result.addError(Issue.V2_SIG_MALFORMED_ADDITIONAL_ATTRIBUTE, additionalAttributeCount);
            return;
        }
    }
}
Also used : ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) BufferUnderflowException(java.nio.BufferUnderflowException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) DigestException(java.security.DigestException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) BufferUnderflowException(java.nio.BufferUnderflowException) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate) DelegatingX509Certificate(com.android.apksigner.core.internal.util.DelegatingX509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 30 with X509Certificate

use of java.security.cert.X509Certificate in project OpenAttestation by OpenAttestation.

the class Pkcs12 method setRsaCredentialX509.

/**
     * Replaces an existing keypair with the same alias or adds a new keypair
     * if one did not already exist.
     * 
     * The chain is optional and if provided it must be the certificates that
     * signed the credential's public key, in order, with the Root CA being LAST.
     * 
     * @param key
     * @param chain
     * @param alias 
     * @param keyPassword
     */
public void setRsaCredentialX509(RsaCredentialX509 key, X509Certificate[] chain, String alias, String keyPassword) throws KeyManagementException {
    try {
        List<String> aliases = Collections.list(keystore.aliases());
        if (aliases.contains(alias)) {
            keystore.deleteEntry(alias);
        }
        X509Certificate[] chain1;
        if (chain != null) {
            chain1 = new X509Certificate[chain.length + 1];
            chain1[0] = key.getCertificate();
            System.arraycopy(chain, 0, chain1, 1, chain.length);
        } else {
            chain1 = new X509Certificate[] { key.getCertificate() };
        }
        keystore.setKeyEntry(alias, key.getPrivateKey(), keyPassword.toCharArray(), chain1);
    } catch (KeyStoreException e) {
        throw new KeyManagementException("Cannot add credential", e);
    }
}
Also used : KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException)

Aggregations

X509Certificate (java.security.cert.X509Certificate)1706 IOException (java.io.IOException)336 CertificateException (java.security.cert.CertificateException)272 ByteArrayInputStream (java.io.ByteArrayInputStream)260 CertificateFactory (java.security.cert.CertificateFactory)251 ArrayList (java.util.ArrayList)232 Certificate (java.security.cert.Certificate)227 KeyStore (java.security.KeyStore)177 PrivateKey (java.security.PrivateKey)150 InputStream (java.io.InputStream)134 File (java.io.File)112 KeyStoreException (java.security.KeyStoreException)112 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)111 GeneralSecurityException (java.security.GeneralSecurityException)100 Test (org.junit.Test)90 List (java.util.List)89 PublicKey (java.security.PublicKey)88 X509TrustManager (javax.net.ssl.X509TrustManager)80 X500Principal (javax.security.auth.x500.X500Principal)76 HashSet (java.util.HashSet)64