java.security.cert.CertificateFactory#getInstance()源码实例Demo

下面列出了java.security.cert.CertificateFactory#getInstance() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: registry   文件: CertificateUtil.java
/**
 * 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;
}
 
源代码2 项目: openjdk-8-source   文件: URICertStore.java
/**
 * 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();
    }
}
 
源代码3 项目: jdk8u-jdk   文件: XMLX509Certificate.java
/**
 * 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);
    }
}
 
源代码4 项目: log4j2-elasticsearch   文件: PemReader.java
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;
}
 
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);
}
 
源代码6 项目: openjdk-jdk8u   文件: XMLX509Certificate.java
/**
 * 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);
    }
}
 
源代码7 项目: athenz   文件: CertificateAuthorityTest.java
@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));
    }
}
 
源代码8 项目: bot-sdk-java   文件: Certificate.java
/**
 * 根据证书地址获取公钥
 * 
 * @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;
    }
}
 
源代码9 项目: pulsar   文件: SecurityUtility.java
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);
    }
}
 
源代码10 项目: jdk8u_jdk   文件: ComodoHacker.java
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];
}
 
源代码11 项目: cyberduck   文件: KeychainCertificateStoreTest.java
@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)));
}
 
源代码12 项目: TencentKona-8   文件: V3Certificate.java
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);
    }
}
 
源代码13 项目: openjdk-8   文件: SignerInfo.java
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;
}
 
源代码14 项目: athenz   文件: AthenzUtilsTest.java
@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));
    }
}
 
源代码15 项目: snowflake-jdbc   文件: SFTrustManagerIT.java
/**
 * 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;
}
 
源代码16 项目: openjdk-8-source   文件: SignerInfo.java
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;
}
 
/**
 * 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);
    }
}
 
源代码18 项目: knox   文件: KnoxSession.java
protected X509Certificate generateCertificateFromBytes(byte[] certBytes) throws CertificateException {
  CertificateFactory factory = CertificateFactory.getInstance("X.509");
  return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));
}
 
源代码19 项目: openjdk-8-source   文件: Identities.java
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;
}
 
源代码20 项目: SecuritySample   文件: CertificatesManager.java
/**
 * 下载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());
}