Search in sources :

Example 16 with X509Certificate

use of java.security.cert.X509Certificate in project jetty.project by eclipse.

the class CertificateValidator method validate.

/**
     * validates a specific certificate inside of the keystore being passed in
     * 
     * @param keyStore the keystore to validate against
     * @param cert the certificate to validate
     * @throws CertificateException if keystore error and unable to validate
     */
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException {
    Certificate[] certChain = null;
    if (cert != null && cert instanceof X509Certificate) {
        ((X509Certificate) cert).checkValidity();
        String certAlias = null;
        try {
            if (keyStore == null) {
                throw new InvalidParameterException("Keystore cannot be null");
            }
            certAlias = keyStore.getCertificateAlias((X509Certificate) cert);
            if (certAlias == null) {
                certAlias = "JETTY" + String.format("%016X", __aliasCount.incrementAndGet());
                keyStore.setCertificateEntry(certAlias, cert);
            }
            certChain = keyStore.getCertificateChain(certAlias);
            if (certChain == null || certChain.length == 0) {
                throw new IllegalStateException("Unable to retrieve certificate chain");
            }
        } catch (KeyStoreException kse) {
            LOG.debug(kse);
            throw new CertificateException("Unable to validate certificate" + (certAlias == null ? "" : " for alias [" + certAlias + "]") + ": " + kse.getMessage(), kse);
        }
        validate(certChain);
    }
}
Also used : InvalidParameterException(java.security.InvalidParameterException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 17 with X509Certificate

use of java.security.cert.X509Certificate in project vert.x by eclipse.

the class SSLHelper method createUntrustRevokedCertTrustManager.

/*
  Proxy the specified trust managers with an implementation checking first the provided certificates
  against the the Certificate Revocation List (crl) before delegating to the original trust managers.
   */
private static TrustManager[] createUntrustRevokedCertTrustManager(TrustManager[] trustMgrs, ArrayList<CRL> crls) {
    trustMgrs = trustMgrs.clone();
    for (int i = 0; i < trustMgrs.length; i++) {
        TrustManager trustMgr = trustMgrs[i];
        if (trustMgr instanceof X509TrustManager) {
            X509TrustManager x509TrustManager = (X509TrustManager) trustMgr;
            trustMgrs[i] = new X509TrustManager() {

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    checkRevoked(x509Certificates);
                    x509TrustManager.checkClientTrusted(x509Certificates, s);
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    checkRevoked(x509Certificates);
                    x509TrustManager.checkServerTrusted(x509Certificates, s);
                }

                private void checkRevoked(X509Certificate[] x509Certificates) throws CertificateException {
                    for (X509Certificate cert : x509Certificates) {
                        for (CRL crl : crls) {
                            if (crl.isRevoked(cert)) {
                                throw new CertificateException("Certificate revoked");
                            }
                        }
                    }
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return x509TrustManager.getAcceptedIssuers();
                }
            };
        }
    }
    return trustMgrs;
}
Also used : CertificateException(java.security.cert.CertificateException) CRL(java.security.cert.CRL) X509Certificate(java.security.cert.X509Certificate)

Example 18 with X509Certificate

use of java.security.cert.X509Certificate in project buck by facebook.

the class ApkBuilderStep method createKeystoreProperties.

private PrivateKeyAndCertificate createKeystoreProperties() throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
    KeystoreProperties keystoreProperties = keystorePropertiesSupplier.get();
    InputStream inputStream = filesystem.getInputStreamForRelativePath(pathToKeystore);
    char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
    try {
        keystore.load(inputStream, keystorePassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new HumanReadableException(e, "%s is an invalid keystore.", pathToKeystore);
    }
    String alias = keystoreProperties.getAlias();
    char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
    Key key = keystore.getKey(alias, keyPassword);
    // key can be null if alias/password is incorrect.
    if (key == null) {
        throw new HumanReadableException("The keystore [%s] key.alias [%s] does not exist or does not identify a key-related " + "entry", pathToKeystore, alias);
    }
    Certificate certificate = keystore.getCertificate(alias);
    return new PrivateKeyAndCertificate((PrivateKey) key, (X509Certificate) certificate);
}
Also used : InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) HumanReadableException(com.facebook.buck.util.HumanReadableException) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 19 with X509Certificate

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

the class CertificateChainValidator method doHandshakeAndValidateServerCertificates.

/**
     * Performs the handshake and server certificates validation
     * Notice a new chain will be rebuilt by tracing the issuer and subject
     * before calling checkServerTrusted().
     * And if the last traced certificate is self issued and it is expired, it
     * will be dropped.
     * @param sslSocket The secure connection socket
     * @param domain The website domain
     * @return An SSL error object if there is an error and null otherwise
     */
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket, String domain) throws IOException {
    // get a valid SSLSession, close the socket if we fail
    SSLSession sslSession = sslSocket.getSession();
    if (!sslSession.isValid()) {
        closeSocketThrowException(sslSocket, "failed to perform SSL handshake");
    }
    // retrieve the chain of the server peer certificates
    Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();
    if (peerCertificates == null || peerCertificates.length == 0) {
        closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
    } else {
        // update the SSL certificate associated with the connection
        if (connection != null) {
            if (peerCertificates[0] != null) {
                connection.setCertificate(new SslCertificate((X509Certificate) peerCertificates[0]));
            }
        }
    }
    return verifyServerDomainAndCertificates((X509Certificate[]) peerCertificates, domain, "RSA");
}
Also used : SSLSession(javax.net.ssl.SSLSession) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 20 with X509Certificate

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

the class RecoverySystem method verifyPackage.

/**
     * Verify the cryptographic signature of a system update package
     * before installing it.  Note that the package is also verified
     * separately by the installer once the device is rebooted into
     * the recovery system.  This function will return only if the
     * package was successfully verified; otherwise it will throw an
     * exception.
     *
     * Verification of a package can take significant time, so this
     * function should not be called from a UI thread.  Interrupting
     * the thread while this function is in progress will result in a
     * SecurityException being thrown (and the thread's interrupt flag
     * will be cleared).
     *
     * @param packageFile  the package to be verified
     * @param listener     an object to receive periodic progress
     * updates as verification proceeds.  May be null.
     * @param deviceCertsZipFile  the zip file of certificates whose
     * public keys we will accept.  Verification succeeds if the
     * package is signed by the private key corresponding to any
     * public key in this file.  May be null to use the system default
     * file (currently "/system/etc/security/otacerts.zip").
     *
     * @throws IOException if there were any errors reading the
     * package or certs files.
     * @throws GeneralSecurityException if verification failed
     */
public static void verifyPackage(File packageFile, ProgressListener listener, File deviceCertsZipFile) throws IOException, GeneralSecurityException {
    long fileLen = packageFile.length();
    RandomAccessFile raf = new RandomAccessFile(packageFile, "r");
    try {
        int lastPercent = 0;
        long lastPublishTime = System.currentTimeMillis();
        if (listener != null) {
            listener.onProgress(lastPercent);
        }
        raf.seek(fileLen - 6);
        byte[] footer = new byte[6];
        raf.readFully(footer);
        if (footer[2] != (byte) 0xff || footer[3] != (byte) 0xff) {
            throw new SignatureException("no signature in file (no footer)");
        }
        int commentSize = (footer[4] & 0xff) | ((footer[5] & 0xff) << 8);
        int signatureStart = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8);
        byte[] eocd = new byte[commentSize + 22];
        raf.seek(fileLen - (commentSize + 22));
        raf.readFully(eocd);
        // end-of-central-directory record.
        if (eocd[0] != (byte) 0x50 || eocd[1] != (byte) 0x4b || eocd[2] != (byte) 0x05 || eocd[3] != (byte) 0x06) {
            throw new SignatureException("no signature in file (bad footer)");
        }
        for (int i = 4; i < eocd.length - 3; ++i) {
            if (eocd[i] == (byte) 0x50 && eocd[i + 1] == (byte) 0x4b && eocd[i + 2] == (byte) 0x05 && eocd[i + 3] == (byte) 0x06) {
                throw new SignatureException("EOCD marker found after start of EOCD");
            }
        }
        // The following code is largely copied from
        // JarUtils.verifySignature().  We could just *call* that
        // method here if that function didn't read the entire
        // input (ie, the whole OTA package) into memory just to
        // compute its message digest.
        BerInputStream bis = new BerInputStream(new ByteArrayInputStream(eocd, commentSize + 22 - signatureStart, signatureStart));
        ContentInfo info = (ContentInfo) ContentInfo.ASN1.decode(bis);
        SignedData signedData = info.getSignedData();
        if (signedData == null) {
            throw new IOException("signedData is null");
        }
        Collection encCerts = signedData.getCertificates();
        if (encCerts.isEmpty()) {
            throw new IOException("encCerts is empty");
        }
        // Take the first certificate from the signature (packages
        // should contain only one).
        Iterator it = encCerts.iterator();
        X509Certificate cert = null;
        if (it.hasNext()) {
            cert = new X509CertImpl((org.apache.harmony.security.x509.Certificate) it.next());
        } else {
            throw new SignatureException("signature contains no certificates");
        }
        List sigInfos = signedData.getSignerInfos();
        SignerInfo sigInfo;
        if (!sigInfos.isEmpty()) {
            sigInfo = (SignerInfo) sigInfos.get(0);
        } else {
            throw new IOException("no signer infos!");
        }
        // Check that the public key of the certificate contained
        // in the package equals one of our trusted public keys.
        HashSet<Certificate> trusted = getTrustedCerts(deviceCertsZipFile == null ? DEFAULT_KEYSTORE : deviceCertsZipFile);
        PublicKey signatureKey = cert.getPublicKey();
        boolean verified = false;
        for (Certificate c : trusted) {
            if (c.getPublicKey().equals(signatureKey)) {
                verified = true;
                break;
            }
        }
        if (!verified) {
            throw new SignatureException("signature doesn't match any trusted key");
        }
        // The signature cert matches a trusted key.  Now verify that
        // the digest in the cert matches the actual file data.
        // The verifier in recovery *only* handles SHA1withRSA
        // signatures.  SignApk.java always uses SHA1withRSA, no
        // matter what the cert says to use.  Ignore
        // cert.getSigAlgName(), and instead use whatever
        // algorithm is used by the signature (which should be
        // SHA1withRSA).
        String da = sigInfo.getDigestAlgorithm();
        String dea = sigInfo.getDigestEncryptionAlgorithm();
        String alg = null;
        if (da == null || dea == null) {
            // fall back to the cert algorithm if the sig one
            // doesn't look right.
            alg = cert.getSigAlgName();
        } else {
            alg = da + "with" + dea;
        }
        Signature sig = Signature.getInstance(alg);
        sig.initVerify(cert);
        // The signature covers all of the OTA package except the
        // archive comment and its 2-byte length.
        long toRead = fileLen - commentSize - 2;
        long soFar = 0;
        raf.seek(0);
        byte[] buffer = new byte[4096];
        boolean interrupted = false;
        while (soFar < toRead) {
            interrupted = Thread.interrupted();
            if (interrupted)
                break;
            int size = buffer.length;
            if (soFar + size > toRead) {
                size = (int) (toRead - soFar);
            }
            int read = raf.read(buffer, 0, size);
            sig.update(buffer, 0, read);
            soFar += read;
            if (listener != null) {
                long now = System.currentTimeMillis();
                int p = (int) (soFar * 100 / toRead);
                if (p > lastPercent && now - lastPublishTime > PUBLISH_PROGRESS_INTERVAL_MS) {
                    lastPercent = p;
                    lastPublishTime = now;
                    listener.onProgress(lastPercent);
                }
            }
        }
        if (listener != null) {
            listener.onProgress(100);
        }
        if (interrupted) {
            throw new SignatureException("verification was interrupted");
        }
        if (!sig.verify(sigInfo.getEncryptedDigest())) {
            throw new SignatureException("signature digest verification failed");
        }
    } finally {
        raf.close();
    }
}
Also used : SignedData(org.apache.harmony.security.pkcs7.SignedData) PublicKey(java.security.PublicKey) SignatureException(java.security.SignatureException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SignerInfo(org.apache.harmony.security.pkcs7.SignerInfo) RandomAccessFile(java.io.RandomAccessFile) ByteArrayInputStream(java.io.ByteArrayInputStream) ContentInfo(org.apache.harmony.security.pkcs7.ContentInfo) X509CertImpl(org.apache.harmony.security.provider.cert.X509CertImpl) Signature(java.security.Signature) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) BerInputStream(org.apache.harmony.security.asn1.BerInputStream) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

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