Search in sources :

Example 26 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project platform_frameworks_base by android.

the class SslCertificate method getDigest.

/**
     * Convenience for UI presentation, not intended as public API.
     */
private static String getDigest(X509Certificate x509Certificate, String algorithm) {
    if (x509Certificate == null) {
        return "";
    }
    try {
        byte[] bytes = x509Certificate.getEncoded();
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] digest = md.digest(bytes);
        return fingerprint(digest);
    } catch (CertificateEncodingException ignored) {
        return "";
    } catch (NoSuchAlgorithmException ignored) {
        return "";
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 27 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project platform_frameworks_base by android.

the class PackageManagerService method compareSignaturesCompat.

/**
     * Used for backward compatibility to make sure any packages with
     * certificate chains get upgraded to the new style. {@code existingSigs}
     * will be in the old format (since they were stored on disk from before the
     * system upgrade) and {@code scannedSigs} will be in the newer format.
     */
private int compareSignaturesCompat(PackageSignatures existingSigs, PackageParser.Package scannedPkg) {
    if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
        return PackageManager.SIGNATURE_NO_MATCH;
    }
    ArraySet<Signature> existingSet = new ArraySet<Signature>();
    for (Signature sig : existingSigs.mSignatures) {
        existingSet.add(sig);
    }
    ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
    for (Signature sig : scannedPkg.mSignatures) {
        try {
            Signature[] chainSignatures = sig.getChainSignatures();
            for (Signature chainSig : chainSignatures) {
                scannedCompatSet.add(chainSig);
            }
        } catch (CertificateEncodingException e) {
            scannedCompatSet.add(sig);
        }
    }
    /*
         * Make sure the expanded scanned set contains all signatures in the
         * existing one.
         */
    if (scannedCompatSet.equals(existingSet)) {
        // Migrate the old signatures to the new scheme.
        existingSigs.assignSignatures(scannedPkg.mSignatures);
        // The new KeySets will be re-added later in the scanning process.
        synchronized (mPackages) {
            mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
        }
        return PackageManager.SIGNATURE_MATCH;
    }
    return PackageManager.SIGNATURE_NO_MATCH;
}
Also used : ArraySet(android.util.ArraySet) Signature(android.content.pm.Signature) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 28 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project XobotOS by xamarin.

the class OpenSSLSocketImpl method startHandshake.

/**
     * Perform the handshake
     *
     * @param full If true, disable handshake cutthrough for a fully synchronous handshake
     */
public synchronized void startHandshake(boolean full) throws IOException {
    synchronized (handshakeLock) {
        checkOpen();
        if (!handshakeStarted) {
            handshakeStarted = true;
        } else {
            return;
        }
    }
    // note that this modifies the global seed, not something specific to the connection
    final int seedLengthInBytes = NativeCrypto.RAND_SEED_LENGTH_IN_BYTES;
    final SecureRandom secureRandom = sslParameters.getSecureRandomMember();
    if (secureRandom == null) {
        NativeCrypto.RAND_load_file("/dev/urandom", seedLengthInBytes);
    } else {
        NativeCrypto.RAND_seed(secureRandom.generateSeed(seedLengthInBytes));
    }
    final boolean client = sslParameters.getUseClientMode();
    final int sslCtxNativePointer = (client) ? sslParameters.getClientSessionContext().sslCtxNativePointer : sslParameters.getServerSessionContext().sslCtxNativePointer;
    this.sslNativePointer = 0;
    boolean exception = true;
    try {
        sslNativePointer = NativeCrypto.SSL_new(sslCtxNativePointer);
        guard.open("close");
        // clients will receive a call back to request certificates.
        if (!client) {
            Set<String> keyTypes = new HashSet<String>();
            for (String enabledCipherSuite : enabledCipherSuites) {
                if (enabledCipherSuite.equals(NativeCrypto.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
                    continue;
                }
                String keyType = CipherSuite.getByName(enabledCipherSuite).getServerKeyType();
                if (keyType != null) {
                    keyTypes.add(keyType);
                }
            }
            for (String keyType : keyTypes) {
                try {
                    setCertificate(sslParameters.getKeyManager().chooseServerAlias(keyType, null, this));
                } catch (CertificateEncodingException e) {
                    throw new IOException(e);
                }
            }
        }
        NativeCrypto.setEnabledProtocols(sslNativePointer, enabledProtocols);
        NativeCrypto.setEnabledCipherSuites(sslNativePointer, enabledCipherSuites);
        if (enabledCompressionMethods.length != 0) {
            NativeCrypto.setEnabledCompressionMethods(sslNativePointer, enabledCompressionMethods);
        }
        if (useSessionTickets) {
            NativeCrypto.SSL_clear_options(sslNativePointer, NativeCrypto.SSL_OP_NO_TICKET);
        }
        if (hostname != null) {
            NativeCrypto.SSL_set_tlsext_host_name(sslNativePointer, hostname);
        }
        boolean enableSessionCreation = sslParameters.getEnableSessionCreation();
        if (!enableSessionCreation) {
            NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer, enableSessionCreation);
        }
        AbstractSessionContext sessionContext;
        if (client) {
            // look for client session to reuse
            ClientSessionContext clientSessionContext = sslParameters.getClientSessionContext();
            sessionContext = clientSessionContext;
            OpenSSLSessionImpl session = getCachedClientSession(clientSessionContext);
            if (session != null) {
                NativeCrypto.SSL_set_session(sslNativePointer, session.sslSessionNativePointer);
            }
        } else {
            sessionContext = sslParameters.getServerSessionContext();
        }
        // setup peer certificate verification
        if (client) {
        // TODO support for anonymous cipher would require us to
        // conditionally use SSL_VERIFY_NONE
        } else {
            // needing client auth takes priority...
            boolean certRequested;
            if (sslParameters.getNeedClientAuth()) {
                NativeCrypto.SSL_set_verify(sslNativePointer, NativeCrypto.SSL_VERIFY_PEER | NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
                certRequested = true;
            // ... over just wanting it...
            } else if (sslParameters.getWantClientAuth()) {
                NativeCrypto.SSL_set_verify(sslNativePointer, NativeCrypto.SSL_VERIFY_PEER);
                certRequested = true;
            // ... and it defaults properly so don't call SSL_set_verify in the common case.
            } else {
                certRequested = false;
            }
            if (certRequested) {
                X509TrustManager trustManager = sslParameters.getTrustManager();
                X509Certificate[] issuers = trustManager.getAcceptedIssuers();
                if (issuers != null && issuers.length != 0) {
                    byte[][] issuersBytes;
                    try {
                        issuersBytes = NativeCrypto.encodeIssuerX509Principals(issuers);
                    } catch (CertificateEncodingException e) {
                        throw new IOException("Problem encoding principals", e);
                    }
                    NativeCrypto.SSL_set_client_CA_list(sslNativePointer, issuersBytes);
                }
            }
        }
        if (client && full) {
            // we want to do a full synchronous handshake, so turn off cutthrough
            NativeCrypto.SSL_clear_mode(sslNativePointer, NativeCrypto.SSL_MODE_HANDSHAKE_CUTTHROUGH);
        }
        // Temporarily use a different timeout for the handshake process
        int savedTimeoutMilliseconds = getSoTimeout();
        if (handshakeTimeoutMilliseconds >= 0) {
            setSoTimeout(handshakeTimeoutMilliseconds);
        }
        int sslSessionNativePointer;
        try {
            sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer, socket.getFileDescriptor$(), this, getSoTimeout(), client);
        } catch (CertificateException e) {
            SSLHandshakeException wrapper = new SSLHandshakeException(e.getMessage());
            wrapper.initCause(e);
            throw wrapper;
        }
        byte[] sessionId = NativeCrypto.SSL_SESSION_session_id(sslSessionNativePointer);
        sslSession = (OpenSSLSessionImpl) sessionContext.getSession(sessionId);
        if (sslSession != null) {
            sslSession.lastAccessedTime = System.currentTimeMillis();
            NativeCrypto.SSL_SESSION_free(sslSessionNativePointer);
        } else {
            if (!enableSessionCreation) {
                // Should have been prevented by NativeCrypto.SSL_set_session_creation_enabled
                throw new IllegalStateException("SSL Session may not be created");
            }
            X509Certificate[] localCertificates = createCertChain(NativeCrypto.SSL_get_certificate(sslNativePointer));
            X509Certificate[] peerCertificates = createCertChain(NativeCrypto.SSL_get_peer_cert_chain(sslNativePointer));
            if (wrappedHost == null) {
                sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates, peerCertificates, super.getInetAddress().getHostName(), super.getPort(), sessionContext);
            } else {
                sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates, peerCertificates, wrappedHost, wrappedPort, sessionContext);
            }
            // if not, putSession later in handshakeCompleted() callback
            if (handshakeCompleted) {
                sessionContext.putSession(sslSession);
            }
        }
        // Restore the original timeout now that the handshake is complete
        if (handshakeTimeoutMilliseconds >= 0) {
            setSoTimeout(savedTimeoutMilliseconds);
        }
        // if not, notifyHandshakeCompletedListeners later in handshakeCompleted() callback
        if (handshakeCompleted) {
            notifyHandshakeCompletedListeners();
        }
        exception = false;
    } catch (SSLProtocolException e) {
        throw new SSLHandshakeException(e);
    } finally {
        // on exceptional exit, treat the socket as closed
        if (exception) {
            close();
        }
    }
}
Also used : SecureRandom(java.security.SecureRandom) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLProtocolException(javax.net.ssl.SSLProtocolException) X509TrustManager(javax.net.ssl.X509TrustManager) HashSet(java.util.HashSet)

Example 29 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project XobotOS by xamarin.

the class SslCertificate method getDigest.

/**
     * Convenience for UI presentation, not intended as public API.
     */
private static String getDigest(X509Certificate x509Certificate, String algorithm) {
    if (x509Certificate == null) {
        return "";
    }
    try {
        byte[] bytes = x509Certificate.getEncoded();
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] digest = md.digest(bytes);
        return fingerprint(digest);
    } catch (CertificateEncodingException ignored) {
        return "";
    } catch (NoSuchAlgorithmException ignored) {
        return "";
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 30 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof KeyPair) {
        return createPemObject(((KeyPair) o).getPrivate());
    } else if (o instanceof PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Object.fromByteArray(((Key) o).getEncoded()));
        if (o instanceof RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else if (o instanceof DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (((PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509V2AttributeCertificate) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    return new PemObject(type, encoding);
}
Also used : X509CRL(java.security.cert.X509CRL) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509V2AttributeCertificate(org.bouncycastle.x509.X509V2AttributeCertificate) X509Certificate(java.security.cert.X509Certificate) PemObject(org.bouncycastle.util.io.pem.PemObject) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey)

Aggregations

CertificateEncodingException (java.security.cert.CertificateEncodingException)210 X509Certificate (java.security.cert.X509Certificate)94 IOException (java.io.IOException)76 Certificate (java.security.cert.Certificate)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)27 KeyStoreException (java.security.KeyStoreException)19 MessageDigest (java.security.MessageDigest)19 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)16 CertificateException (java.security.cert.CertificateException)14 BigInteger (java.math.BigInteger)11 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)10 Bundle (android.os.Bundle)9 PublicKey (java.security.PublicKey)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 File (java.io.File)8 PrivateKey (java.security.PrivateKey)8 DEROctetString (org.bouncycastle.asn1.DEROctetString)8