当前位置: 首页>>代码示例>>Java>>正文


Java KeyStore.setCertificateEntry方法代码示例

本文整理汇总了Java中java.security.KeyStore.setCertificateEntry方法的典型用法代码示例。如果您正苦于以下问题:Java KeyStore.setCertificateEntry方法的具体用法?Java KeyStore.setCertificateEntry怎么用?Java KeyStore.setCertificateEntry使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.security.KeyStore的用法示例。


在下文中一共展示了KeyStore.setCertificateEntry方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createKeyManagerFactory

import java.security.KeyStore; //导入方法依赖的package包/类
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
开发者ID:PacktPublishing,项目名称:MQTT-Essentials-A-Lightweight-IoT-Protocol,代码行数:22,代码来源:SecurityHelper.java

示例2: getTrustManager

import java.security.KeyStore; //导入方法依赖的package包/类
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];
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:22,代码来源:ComodoHacker.java

示例3: addCertificate

import java.security.KeyStore; //导入方法依赖的package包/类
private SSLSocketFactory addCertificate(InputStream inputStream) throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, KeyManagementException {
    // loading CAs from an InputStream
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate ca;
    try {
        ca = cf.generateCertificate(inputStream);
    } finally {
        inputStream.close();
    }

    // creating a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // creating a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // creating an SSLSocketFactory that uses our TrustManager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}
 
开发者ID:sinhaDroid,项目名称:BlogBookApp,代码行数:28,代码来源:MyWebService.java

示例4: installCertificates

import java.security.KeyStore; //导入方法依赖的package包/类
private void installCertificates(Path path, KeyStore keyStore)
    throws IOException, CertificateException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

  try (DirectoryStream<Path> paths = Files.newDirectoryStream(path, "*.{crt,pem}")) {
    for (Path certPath : paths) {
      logger.info("installing cert from path {}", certPath.toRealPath());
      if (Files.isRegularFile(certPath)) {
        try (InputStream inputStream = Files.newInputStream(certPath)) {
          Certificate cert = certificateFactory.generateCertificate(inputStream);
          String alias = certPath.getFileName().toString();
          keyStore.setCertificateEntry(alias, cert);
          logger.info("ok, installed cert with alias {} from path {}", alias,
              certPath.toRealPath());
        } catch (Exception e) {
          logger.warn("error, skipping cert, path {} {}", certPath.toRealPath(), e.getMessage());
        }
      } else {
        logger.info("skipping cert, not a regular file {}", certPath.toRealPath());
      }
    }
  }
}
 
开发者ID:dehora,项目名称:outland,代码行数:24,代码来源:CertificateLoader.java

示例5: createAndInitKeyManagerFactory

import java.security.KeyStore; //导入方法依赖的package包/类
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
  X509Certificate certHolder = certificateConverter.getCertificate((X509CertificateHolder) readPEMFile(cert));

  Object keyObject = readPEMFile(privateKey);

  char[] passwordCharArray = "".toCharArray();
  if (!StringUtils.isEmpty(password)) {
    passwordCharArray = password.toCharArray();
  }

  JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");

  KeyPair key;
  if (keyObject instanceof PEMEncryptedKeyPair) {
    PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
    key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
  } else {
    key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
  }

  KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  clientKeyStore.load(null, null);
  clientKeyStore.setCertificateEntry("cert", certHolder);
  clientKeyStore.setKeyEntry("private-key", key.getPrivate(), passwordCharArray, new Certificate[] { certHolder });

  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(clientKeyStore, passwordCharArray);
  return keyManagerFactory;
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:30,代码来源:CertPemClientCredentials.java

示例6: createTrustStore

import java.security.KeyStore; //导入方法依赖的package包/类
public static void createTrustStore(String filename,
                                    String password, String alias,
                                    Certificate cert)
  throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setCertificateEntry(alias, cert);
  saveKeyStore(ks, filename, password);
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:9,代码来源:KeyStoreTestUtil.java

示例7: trustManagerForCertificates

import java.security.KeyStore; //导入方法依赖的package包/类
private static X509TrustManager trustManagerForCertificates(InputStream in)
        throws GeneralSecurityException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
        throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    char[] password = "password".toCharArray(); // Any password will work.
    KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
        String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(certificateAlias, certificate);
    }

    // Use it to build an X509 trust manager.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:"
                + Arrays.toString(trustManagers));
    }
    return (X509TrustManager) trustManagers[0];
}
 
开发者ID:jtduan,项目名称:common-spider,代码行数:32,代码来源:HttpsUtil.java

示例8: trustManagerForCertificates

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:52,代码来源:CustomTrust.java

示例9: createTrustStore

import java.security.KeyStore; //导入方法依赖的package包/类
public static void createTrustStore(String filename,
    String password, String alias,
    Certificate cert)
    throws GeneralSecurityException, IOException {
  KeyStore ks = createEmptyKeyStore();
  ks.setCertificateEntry(alias, cert);
  saveKeyStore(ks, filename, password);
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:9,代码来源:KeyStoreTestUtil.java

示例10: getClient

import java.security.KeyStore; //导入方法依赖的package包/类
public static OkHttpClient.Builder getClient(SatispayContext satispayContext) {
    OkHttpClient.Builder okHttpClientBuilder;
    okHttpClientBuilder = new OkHttpClient.Builder();

    // ==> the SSL context is build only in environments different from PROD / STAGING, where the server cert is self signed
    String serverCert = satispayContext.getServerCert();
    if (serverCert != null) {
        try {
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore;
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", CryptoUtils.certificateX509(serverCert));

            String trustManagerDefaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerDefaultAlgorithm);
            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            okHttpClientBuilder.sslSocketFactory(sslSocketFactory);
        } catch (Exception e) {
            ProtoLogger.error("!!! Error generating TLS context !!!");
        }
    }
    okHttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.writeTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.readTimeout(30, TimeUnit.SECONDS);
    return okHttpClientBuilder;
}
 
开发者ID:satispay,项目名称:in-store-api-java-sdk,代码行数:32,代码来源:NetworkUtilities.java

示例11: execute0

import java.security.KeyStore; //导入方法依赖的package包/类
@Override
protected Object execute0() throws Exception {
    File realKsFile = new File(IoUtil.expandFilepath(ksFile));
    KeyStore ks = KeyStore.getInstance(ksType);
    char[] password = readPasswordIfNotSet(ksPwd);

    Set<String> aliases = new HashSet<>(10);
    if (realKsFile.exists()) {
        FileInputStream inStream = new FileInputStream(realKsFile);
        try {
            ks.load(inStream, password);
        } finally {
            inStream.close();
        }

        Enumeration<String> strs = ks.aliases();
        while (strs.hasMoreElements()) {
            aliases.add(strs.nextElement());
        }
    } else {
        ks.load(null);
    }

    for (String certFile : certFiles) {
        X509Certificate cert = X509Util.parseCert(certFile);
        String baseAlias = X509Util.getCommonName(cert.getSubjectX500Principal());
        String alias = baseAlias;
        int idx = 2;
        while (aliases.contains(alias)) {
            alias = baseAlias + "-" + (idx++);
        }
        ks.setCertificateEntry(alias, cert);
        aliases.add(alias);
    }

    ByteArrayOutputStream bout = new ByteArrayOutputStream(4096);
    ks.store(bout, password);
    saveVerbose("saved keystore to file", realKsFile, bout.toByteArray());
    return null;
}
 
开发者ID:xipki,项目名称:xitk,代码行数:41,代码来源:ImportCertCmd.java

示例12: trustCertificate

import java.security.KeyStore; //导入方法依赖的package包/类
private void trustCertificate(Certificate cert, String deviceLabel) throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
    KeyStore ts = getKeyStore();

    Log.i(TAG, "Adding certificate ID " + deviceLabel + " to Trust store (" + trustStorePath + "): " + cert);
    ts.setCertificateEntry(deviceLabel, cert);

    ts.store(new FileOutputStream(trustStorePath), null);
}
 
开发者ID:RomascuAndrei,项目名称:BTNotifierAndroid,代码行数:9,代码来源:SslUtils.java

示例13: getSSLContext

import java.security.KeyStore; //导入方法依赖的package包/类
private SSLContext getSSLContext(boolean authnRequired) throws Exception {
    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

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

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

    // import the trusted cert
    ks.setCertificateEntry("RSA Export Signer", trustedCert);

    if (authnRequired) {
        // 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(serverCertStr.getBytes());
        Certificate serverCert = cf.generateCertificate(is);

        Certificate[] chain = new Certificate[2];
        chain[0] = serverCert;
        chain[1] = trustedCert;

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

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

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (authnRequired) {
        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;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:53,代码来源:RSAExport.java

示例14: getSSLContext

import java.security.KeyStore; //导入方法依赖的package包/类
private SSLContext getSSLContext() throws Exception {

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

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

        // import the trused cert
        ByteArrayInputStream is =
                    new ByteArrayInputStream(trustedCertStr.getBytes());
        Certificate trusedCert = cf.generateCertificate(is);
        is.close();
        ts.setCertificateEntry("rsa-trusted-2048", trusedCert);

        // generate the private key.
        String keySpecStr = targetPrivateKey;
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey = (RSAPrivateKey)kf.generatePrivate(priKeySpec);

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

        // import the key entry.
        ks.setKeyEntry("rsa-key-2048", priKey, passphrase, chain);

        // create SSL context
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);

        SSLContext sslCtx = SSLContext.getInstance("TLSv1");
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslCtx;
    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:44,代码来源:DHEKeySizing.java

示例15: generateSSLContext

import java.security.KeyStore; //导入方法依赖的package包/类
private static SSLContext generateSSLContext(String trustedCertStr,
        String keyCertStr, String keySpecStr) 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 trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trustedCertStr != null) {
        is = new ByteArrayInputStream(trustedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        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();

        // It's not allowed to send MD2 signed certificate to peer,
        // even it may be a trusted certificate. Then we will not
        // place the trusted certficate in the chain.
        Certificate[] chain = new Certificate[1];
        chain[0] = keyCert;

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

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

    SSLContext ctx = SSLContext.getInstance(tlsProtocol);
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

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

    return ctx;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:62,代码来源:MD2InTrustAnchor.java


注:本文中的java.security.KeyStore.setCertificateEntry方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。