Search in sources :

Example 26 with CertificateFactory

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

the class V2SchemeVerifier method parseSigners.

/**
     * Parses each signer in the provided APK Signature Scheme v2 block and populates
     * {@code signerInfos} of the provided {@code result}.
     *
     * <p>This verifies signatures over {@code signed-data} block contained in each signer block.
     * However, this does not verify the integrity of the rest of the APK but rather simply reports
     * the expected digests of the rest of the APK (see {@code contentDigestsToVerify}).
     */
private static void parseSigners(ByteBuffer apkSignatureSchemeV2Block, Set<ContentDigestAlgorithm> contentDigestsToVerify, Result result) {
    ByteBuffer signers;
    try {
        signers = getLengthPrefixedSlice(apkSignatureSchemeV2Block);
    } catch (IOException e) {
        result.addError(Issue.V2_SIG_MALFORMED_SIGNERS);
        return;
    }
    if (!signers.hasRemaining()) {
        result.addError(Issue.V2_SIG_NO_SIGNERS);
        return;
    }
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("Failed to obtain X.509 CertificateFactory", e);
    }
    int signerCount = 0;
    while (signers.hasRemaining()) {
        int signerIndex = signerCount;
        signerCount++;
        Result.SignerInfo signerInfo = new Result.SignerInfo();
        signerInfo.index = signerIndex;
        result.signers.add(signerInfo);
        try {
            ByteBuffer signer = getLengthPrefixedSlice(signers);
            parseSigner(signer, certFactory, signerInfo, contentDigestsToVerify);
        } catch (IOException | BufferUnderflowException e) {
            signerInfo.addError(Issue.V2_SIG_MALFORMED_SIGNER);
            return;
        }
    }
}
Also used : CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) CertificateFactory(java.security.cert.CertificateFactory) BufferUnderflowException(java.nio.BufferUnderflowException)

Example 27 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 28 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 29 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)

Example 30 with CertificateFactory

use of java.security.cert.CertificateFactory in project okhttp-OkGo by jeasonlzy.

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 = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certStream : certificates) {
            String certificateAlias = Integer.toString(index++);
            // 证书工厂根据证书文件的流生成证书 cert
            Certificate cert = certificateFactory.generateCertificate(certStream);
            // 将 cert 作为可信证书放入到keyStore中
            keyStore.setCertificateEntry(certificateAlias, cert);
            try {
                if (certStream != null)
                    certStream.close();
            } catch (IOException e) {
                OkLogger.e(e);
            }
        }
        //我们创建一个默认类型的TrustManagerFactory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        //用我们之前的keyStore实例初始化TrustManagerFactory,这样tmf就会信任keyStore中的证书
        tmf.init(keyStore);
        //通过tmf获取TrustManager数组,TrustManager也会信任keyStore中的证书
        return tmf.getTrustManagers();
    } catch (Exception e) {
        OkLogger.e(e);
    }
    return null;
}
Also used : InputStream(java.io.InputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

CertificateFactory (java.security.cert.CertificateFactory)550 X509Certificate (java.security.cert.X509Certificate)409 ByteArrayInputStream (java.io.ByteArrayInputStream)372 Certificate (java.security.cert.Certificate)272 CertificateException (java.security.cert.CertificateException)120 KeyFactory (java.security.KeyFactory)103 PrivateKey (java.security.PrivateKey)93 InputStream (java.io.InputStream)92 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)86 IOException (java.io.IOException)80 KeyStore (java.security.KeyStore)77 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)67 Entry (java.security.KeyStore.Entry)59 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)59 KeyStoreException (java.security.KeyStoreException)49 ArrayList (java.util.ArrayList)49 FileInputStream (java.io.FileInputStream)47 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)35 File (java.io.File)23 HashSet (java.util.HashSet)21