Search in sources :

Example 56 with CertificateFactory

use of java.security.cert.CertificateFactory in project okhttputils by hongyangAndroid.

the class HttpsUtils method prepareTrustManager.

private static TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates == null || certificates.length <= 0)
        return null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
            }
        }
        TrustManagerFactory trustManagerFactory = null;
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        return trustManagers;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Example 57 with CertificateFactory

use of java.security.cert.CertificateFactory in project hudson-2.x by hudson.

the class UpdateSite method verifySignature.

/**
     * Verifies the signature in the update center data file.
     */
private boolean verifySignature(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject signature = o.getJSONObject("signature");
    if (signature.isNullObject()) {
        LOGGER.severe("No signature block found");
        return false;
    }
    o.remove("signature");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    {
        // load and verify certificates
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        for (Object cert : o.getJSONArray("certificates")) {
            X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
            c.checkValidity();
            certs.add(c);
        }
        // all default root CAs in JVM are trusted, plus certs bundled in Hudson
        Set<TrustAnchor> anchors = CertificateUtil.getDefaultRootCAs();
        ServletContext context = Hudson.getInstance().servletContext;
        for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
            // skip text files that are meant to be documentation
            if (cert.endsWith(".txt"))
                continue;
            anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(context.getResourceAsStream(cert)), null));
        }
        CertificateUtil.validatePath(certs);
    }
    // this is for computing a digest to check sanity
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);
    // this is for computing a signature
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(certs.get(0));
    SignatureOutputStream sos = new SignatureOutputStream(sig);
    JSONCanonicalUtils.write(o, new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8"));
    // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
    // (which is more likely than someone tampering with update center), we can tell
    String computedDigest = new String(Base64.encode(sha1.digest()));
    String providedDigest = signature.getString("digest");
    if (!computedDigest.equalsIgnoreCase(providedDigest)) {
        LOGGER.severe("Digest mismatch: " + computedDigest + " vs " + providedDigest);
        return false;
    }
    if (!sig.verify(Base64.decode(signature.getString("signature").toCharArray()))) {
        LOGGER.severe("Signature in the update center doesn't match with the certificate");
        return false;
    }
    return true;
}
Also used : TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) Set(java.util.Set) ArrayList(java.util.ArrayList) TrustAnchor(java.security.cert.TrustAnchor) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) JSONObject(net.sf.json.JSONObject) SignatureOutputStream(org.jvnet.hudson.crypto.SignatureOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestOutputStream(java.security.DigestOutputStream) Signature(java.security.Signature) ServletContext(javax.servlet.ServletContext) JSONObject(net.sf.json.JSONObject) OutputStreamWriter(java.io.OutputStreamWriter) MessageDigest(java.security.MessageDigest) NullOutputStream(org.apache.commons.io.output.NullOutputStream)

Example 58 with CertificateFactory

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

the class X509Builder method build.

public X509Certificate build() {
    if (certificateVersion == null) {
        v3();
    }
    if (certificateValidity == null) {
        // 1 year default
        expires(365, TimeUnit.DAYS);
    }
    if (certificateSerialNumber == null) {
        randomSerial();
    }
    if (certificateSubjectName == null) {
        if (commonName != null || organizationUnit != null || organizationName != null || country != null) {
            try {
                subjectName(new X500Name(commonName, organizationUnit, organizationName, country));
            } catch (Exception e) {
                fault(e, "commonName(%s) organizationUnit(%s) organizationName(%s) country(%s)", commonName, organizationUnit, organizationName, country);
            }
        }
    }
    if (certificateIssuerName == null) {
        //}
        if (commonName != null || organizationUnit != null || organizationName != null || country != null) {
            try {
                issuerName(new X500Name(commonName, organizationUnit, organizationName, country));
            } catch (Exception e) {
                fault(e, "commonName(%s) organizationUnit(%s) organizationName(%s) country(%s)", commonName, organizationUnit, organizationName, country);
            }
        }
    }
    if (subjectPublicKey == null) {
        fault("missing subject public key");
    }
    // Note: alternativeName is optional so we don't have any defaults or errors for it here
    if (algorithm == null) {
        // algorithm.getName() == SHA256withRSA
        algorithm(new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid));
    }
    //}
    try {
        if (getFaults().isEmpty()) {
            // Sign the cert to identify the algorithm that's used.
            X509CertImpl cert = new X509CertImpl(info);
            // NoSuchAlgorithMException, InvalidKeyException, NoSuchProviderException, , SignatureException
            cert.sign(issuerPrivateKey, algorithm.getName());
            /*
                 * for some unknown reason, if we return the "cert" now then all 
                 * the optioanl fields such as getBasicConstraints() and 
                 * getKeyUsage() are missing even though they are included if you 
                 * call getEncoded() ... but if you re-create the certificate
                 * then those fields are present in the re-created certificate.
                 */
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert2 = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));
            return cert2;
        }
        return null;
    } catch (Exception e) {
        fault(e, "cannot sign certificate");
        return null;
    } finally {
        done();
    }
}
Also used : CertificateAlgorithmId(sun.security.x509.CertificateAlgorithmId) AlgorithmId(sun.security.x509.AlgorithmId) ByteArrayInputStream(java.io.ByteArrayInputStream) X509CertImpl(sun.security.x509.X509CertImpl) X500Name(sun.security.x509.X500Name) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 59 with CertificateFactory

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

the class X509Util method decodeDerCertificate.

/**
     * Reads a DER-encoded certificate and creates a corresponding X509Certificate
     * object.
     * @param certificateBytes
     * @return
     * @throws CertificateException 
     */
public static X509Certificate decodeDerCertificate(byte[] certificateBytes) throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
    return cert;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 60 with CertificateFactory

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

the class X509CertificateDerProvider method readFrom.

@Override
public X509Certificate readFrom(Class<X509Certificate> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    try {
        // instead of using X509Util.decodeDerCertificate(byte[]) here we inline it because we have an inputstream instead
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(entityStream);
        return cert;
    } catch (CertificateException e) {
        throw new IOException(e);
    }
}
Also used : CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Aggregations

CertificateFactory (java.security.cert.CertificateFactory)588 X509Certificate (java.security.cert.X509Certificate)439 ByteArrayInputStream (java.io.ByteArrayInputStream)386 Certificate (java.security.cert.Certificate)276 CertificateException (java.security.cert.CertificateException)132 InputStream (java.io.InputStream)115 KeyFactory (java.security.KeyFactory)103 PrivateKey (java.security.PrivateKey)94 IOException (java.io.IOException)88 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)86 KeyStore (java.security.KeyStore)82 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)67 FileInputStream (java.io.FileInputStream)60 Entry (java.security.KeyStore.Entry)59 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)59 ArrayList (java.util.ArrayList)52 KeyStoreException (java.security.KeyStoreException)51 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)38 File (java.io.File)29 HashSet (java.util.HashSet)21