Java Code Examples for java.security.cert.CertificateFactory#getInstance()

The following examples show how to use java.security.cert.CertificateFactory#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PemReader.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
private static List<X509Certificate> readCertificateChain(FileInputStream certificateChainFis)
        throws IOException, GeneralSecurityException
{
    String contents = readFile(certificateChainFis);

    Matcher matcher = CERT_PATTERN.matcher(contents);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    List<X509Certificate> certificates = new ArrayList<>();

    int start = 0;
    while (matcher.find(start)) {
        byte[] buffer = base64Decode(matcher.group(1));
        certificates.add((X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(buffer)));
        start = matcher.end();
    }

    return certificates;
}
 
Example 2
Source File: ComodoHacker.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static X509TrustManager getTrustManager() throws Exception {
    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trusted cert
    try (ByteArrayInputStream is =
            new ByteArrayInputStream(trustedCertStr.getBytes())) {
        Certificate trustedCert = cf.generateCertificate(is);
        ks.setCertificateEntry("RSA Export Signer", trustedCert);
    }

    // create the trust manager
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    return (X509TrustManager)tmf.getTrustManagers()[0];
}
 
Example 3
Source File: SecurityUtility.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public static X509Certificate[] loadCertificatesFromPemStream(InputStream inStream) throws KeyManagementException  {
    if (inStream == null) {
        return null;
    }
    CertificateFactory cf;
    try {
        if (inStream.markSupported()) {
            inStream.reset();
        }
        cf = CertificateFactory.getInstance("X.509");
        Collection<X509Certificate> collection = (Collection<X509Certificate>) cf.generateCertificates(inStream);
        return collection.toArray(new X509Certificate[collection.size()]);
    } catch (CertificateException | IOException e) {
        throw new KeyManagementException("Certificate loading error", e);
    }
}
 
Example 4
Source File: Certificate.java    From bot-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * 根据证书地址获取公钥
 * 
 * @param signaturecerturl
 *            证书地址
 * @return PublicKey 公钥
 */
public static PublicKey getPublicKeyFromUrl(String signaturecerturl) {
    if (!isBaiduDomain(signaturecerturl)) {
        return null;
    }
    try {
        URL url = new URL(signaturecerturl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(3 * 1000);
        InputStream inputStream = connection.getInputStream();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
        PublicKey publicKey = certificate.getPublicKey();
        return publicKey;
    } catch (Exception e) {
        return null;
    }
}
 
Example 5
Source File: CertificateAuthorityTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticateRoleCertificate() throws Exception {
    CertificateAuthority authority = new CertificateAuthority();
    authority.initialize();

    try (InputStream inStream = new FileInputStream("src/test/resources/valid_email_x509.cert")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);

        X509Certificate[] certs = new X509Certificate[1];
        certs[0] = cert;
        Principal principal = authority.authenticate(certs, null);
        assertNotNull(principal);
        assertEquals("athens", principal.getDomain());
        assertEquals("zts", principal.getName());
        assertEquals("sports:role.readers", principal.getRoles().get(0));
    }
}
 
Example 6
Source File: XMLX509Certificate.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method getX509Certificate
 *
 * @return the x509 certificate
 * @throws XMLSecurityException
 */
public X509Certificate getX509Certificate() throws XMLSecurityException {
    try {
        byte certbytes[] = this.getCertificateBytes();
        CertificateFactory certFact =
            CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
        X509Certificate cert =
            (X509Certificate) certFact.generateCertificate(
                new ByteArrayInputStream(certbytes)
            );

        if (cert != null) {
            return cert;
        }

        return null;
    } catch (CertificateException ex) {
        throw new XMLSecurityException("empty", ex);
    }
}
 
Example 7
Source File: ValidateTargetConstraints.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void createPath(String[] certs) throws Exception {
    TrustAnchor anchor = new TrustAnchor(getCertFromFile(certs[0]), null);
    List list = new ArrayList();
    for (int i = 1; i < certs.length; i++) {
        list.add(0, getCertFromFile(certs[i]));
    }
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    path = cf.generateCertPath(list);

    Set anchors = Collections.singleton(anchor);
    params = new PKIXParameters(anchors);
    params.setRevocationEnabled(false);
    X509CertSelector sel = new X509CertSelector();
    sel.setSerialNumber(new BigInteger("1427"));
    params.setTargetCertConstraints(sel);
}
 
Example 8
Source File: CertificateUtil.java    From registry with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an RSAPublicKey from the provided PEM encoding.
 *
 * @param pem
 *          - the pem encoding from config without the header and footer
 * @return RSAPublicKey the RSA public key
 * @throws ServletException thrown if a processing error occurred
 */
public static RSAPublicKey parseRSAPublicKey(String pem) throws ServletException {
    String fullPem = PEM_HEADER + pem + PEM_FOOTER;
    PublicKey key = null;
    try {
        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream is = new ByteArrayInputStream(
                fullPem.getBytes("UTF8"));

        X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
        key = cer.getPublicKey();
    } catch (CertificateException ce) {
        String message = null;
        if (pem.startsWith(PEM_HEADER)) {
            message = "CertificateException - be sure not to include PEM header "
                    + "and footer in the PEM configuration element.";
        } else {
            message = "CertificateException - PEM may be corrupt";
        }
        throw new ServletException(message, ce);
    } catch (UnsupportedEncodingException uee) {
        throw new ServletException(uee);
    }
    return (RSAPublicKey) key;
}
 
Example 9
Source File: XMLX509Certificate.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method getX509Certificate
 *
 * @return the x509 certificate
 * @throws XMLSecurityException
 */
public X509Certificate getX509Certificate() throws XMLSecurityException {
    try {
        byte certbytes[] = this.getCertificateBytes();
        CertificateFactory certFact =
            CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
        X509Certificate cert =
            (X509Certificate) certFact.generateCertificate(
                new ByteArrayInputStream(certbytes)
            );

        if (cert != null) {
            return cert;
        }

        return null;
    } catch (CertificateException ex) {
        throw new XMLSecurityException("empty", ex);
    }
}
 
Example 10
Source File: URICertStore.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a URICertStore.
 *
 * @param parameters specifying the URI
 */
URICertStore(CertStoreParameters params)
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
    super(params);
    if (!(params instanceof URICertStoreParameters)) {
        throw new InvalidAlgorithmParameterException
            ("params must be instanceof URICertStoreParameters");
    }
    this.uri = ((URICertStoreParameters) params).uri;
    // if ldap URI, use an LDAPCertStore to fetch certs and CRLs
    if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) {
        ldap = true;
        ldapHelper = CertStoreHelper.getInstance("LDAP");
        ldapCertStore = ldapHelper.getCertStore(uri);
        ldapPath = uri.getPath();
        // strip off leading '/'
        if (ldapPath.charAt(0) == '/') {
            ldapPath = ldapPath.substring(1);
        }
    }
    try {
        factory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException();
    }
}
 
Example 11
Source File: SFTrustManagerIT.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Read certificates from a file.
 *
 * @param filename file name under resources directory
 * @return an array of X509Certificate
 * @throws Throwable raise if any error occurs
 */
private List<X509Certificate> getX509CertificatesFromFile(String filename) throws Throwable
{
  CertificateFactory fact = CertificateFactory.getInstance("X.509");
  List<X509Certificate> certList = new ArrayList<>();
  for (Certificate cert : fact.generateCertificates(getFile(filename)))
  {
    certList.add((X509Certificate) cert);
  }
  return certList;
}
 
Example 12
Source File: AthenzUtilsTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsRoleCertificateRoleCertificate() throws Exception {
    try (InputStream inStream = new FileInputStream("src/test/resources/valid_email_x509.cert")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);

        assertTrue(AthenzUtils.isRoleCertificate(cert));
    }
}
 
Example 13
Source File: SignerInfo.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Timestamp getTimestamp()
    throws IOException, NoSuchAlgorithmException, SignatureException,
           CertificateException
{
    if (timestamp != null || !hasTimestamp)
        return timestamp;

    if (unauthenticatedAttributes == null) {
        hasTimestamp = false;
        return null;
    }
    PKCS9Attribute tsTokenAttr =
        unauthenticatedAttributes.getAttribute(
            PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
    if (tsTokenAttr == null) {
        hasTimestamp = false;
        return null;
    }

    PKCS7 tsToken = new PKCS7((byte[])tsTokenAttr.getValue());
    // Extract the content (an encoded timestamp token info)
    byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
    // Extract the signer (the Timestamping Authority)
    // while verifying the content
    SignerInfo[] tsa = tsToken.verify(encTsTokenInfo);
    // Expect only one signer
    ArrayList<X509Certificate> chain = tsa[0].getCertificateChain(tsToken);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath tsaChain = cf.generateCertPath(chain);
    // Create a timestamp token info object
    TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
    // Check that the signature timestamp applies to this signature
    verifyTimestamp(tsTokenInfo);
    // Create a timestamp object
    timestamp = new Timestamp(tsTokenInfo.getDate(), tsaChain);
    return timestamp;
}
 
Example 14
Source File: SignerInfo.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public Timestamp getTimestamp()
    throws IOException, NoSuchAlgorithmException, SignatureException,
           CertificateException
{
    if (timestamp != null || !hasTimestamp)
        return timestamp;

    if (unauthenticatedAttributes == null) {
        hasTimestamp = false;
        return null;
    }
    PKCS9Attribute tsTokenAttr =
        unauthenticatedAttributes.getAttribute(
            PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
    if (tsTokenAttr == null) {
        hasTimestamp = false;
        return null;
    }

    PKCS7 tsToken = new PKCS7((byte[])tsTokenAttr.getValue());
    // Extract the content (an encoded timestamp token info)
    byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
    // Extract the signer (the Timestamping Authority)
    // while verifying the content
    SignerInfo[] tsa = tsToken.verify(encTsTokenInfo);
    // Expect only one signer
    ArrayList<X509Certificate> chain = tsa[0].getCertificateChain(tsToken);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath tsaChain = cf.generateCertPath(chain);
    // Create a timestamp token info object
    TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
    // Check that the signature timestamp applies to this signature
    verifyTimestamp(tsTokenInfo);
    // Create a timestamp object
    timestamp = new Timestamp(tsTokenInfo.getDate(), tsaChain);
    return timestamp;
}
 
Example 15
Source File: IdentityApplicationManagementUtil.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Generate thumbprint of certificate
 *
 * @param encodedCert Base64 encoded certificate
 * @return Decoded <code>Certificate</code>
 * @throws java.security.cert.CertificateException Error when decoding certificate
 */
public static Certificate decodeCertificate(String encodedCert) throws CertificateException {

    if (encodedCert != null) {
        byte[] bytes = Base64.decode(encodedCert);
        CertificateFactory factory = CertificateFactory.getInstance(IdentityApplicationConstants.CERTIFICATE_TYPE);
        X509Certificate cert = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(bytes));
        return cert;
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}
 
Example 16
Source File: V3Certificate.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static X509Certificate generateCertificate(String certFile) {
    try (InputStream inStrm = new FileInputStream(certFile)) {
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate x2
                = (X509Certificate) cf.generateCertificate(inStrm);
        return x2;
    } catch (CertificateException | IOException e) {
        throw new RuntimeException("Exception while "
                + "genrating certificate for " + certFile, e);
    }
}
 
Example 17
Source File: KeychainCertificateStoreTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testTrustedHostnameMismatch() throws Exception {
    final KeychainCertificateStore k = new KeychainCertificateStore();
    InputStream inStream = new FileInputStream("src/test/resources/OXxlRDVcWqdPEvFm.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
    assertFalse(k.verify(new DisabledCertificateTrustCallback(), "s.test.cyberduck.ch", Collections.singletonList(cert)));
}
 
Example 18
Source File: Identities.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, byte[] modulus,
        byte[] privateExponent, char[] passphrase) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    ByteArrayInputStream is =
                new ByteArrayInputStream(trusedCertStr.getBytes());
    Certificate trusedCert = cf.generateCertificate(is);
    is.close();

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    ks.setCertificateEntry("RSA Export Signer", trusedCert);

    if (keyCertStr != null) {
        // generate the private key.
        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(
                                        new BigInteger(modulus),
                                        new BigInteger(privateExponent));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = new Certificate[2];
        chain[0] = keyCert;
        chain[1] = trusedCert;

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");

    if (keyCertStr != null) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 19
Source File: KnoxSession.java    From knox with Apache License 2.0 4 votes vote down vote up
protected X509Certificate generateCertificateFromBytes(byte[] certBytes) throws CertificateException {
  CertificateFactory factory = CertificateFactory.getInstance("X.509");
  return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));
}
 
Example 20
Source File: CertificatesManager.java    From SecuritySample with Apache License 2.0 2 votes vote down vote up
/**
 * 下载X509证书文件
 *
 * @param urlString
 * @return
 * @throws CertificateException
 * @throws IOException
 */
public static X509Certificate downloadCaIssuersCert(String urlString) throws CertificateException, IOException {
    URL url = new URL(urlString);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(url.openStream());
}