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


Java KeyStore.getInstance方法代码示例

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


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

示例1: if

import java.security.KeyStore; //导入方法依赖的package包/类
private static ServerSocketFactory getServerSocketFactory
               (boolean useSSL) throws Exception {
    if (useSSL) {
        SSLServerSocketFactory ssf = null;
        // set up key manager to do server authentication
        SSLContext ctx;
        KeyManagerFactory kmf;
        KeyStore ks;
        char[] passphrase = passwd.toCharArray();

        ctx = SSLContext.getInstance("TLS");
        kmf = KeyManagerFactory.getInstance("SunX509");
        ks = KeyStore.getInstance("JKS");

        ks.load(new FileInputStream(System.getProperty(
                    "javax.net.ssl.keyStore")), passphrase);
        kmf.init(ks, passphrase);
        ctx.init(kmf.getKeyManagers(), null, null);

        ssf = ctx.getServerSocketFactory();
        return ssf;
    } else {
        return ServerSocketFactory.getDefault();
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:26,代码来源:ClientHelloRead.java

示例2: createKeys

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Creates a public and private key and stores it using the AndroidKeyStore,
 * so that only this application will be able to access the keys.
 */
@SuppressWarnings("deprecation")
public void createKeys() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    if (keyStore.containsAlias(alias)) {
        Log.d(TAG, "[containsAlias]");
        return;
    }

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
        .setAlias(alias)
        .setSubject(new X500Principal("CN=" + alias))
        .setSerialNumber(BigInteger.TEN)
        .setStartDate(start.getTime())
        .setEndDate(end.getTime())
        .build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE_RSA, ANDROID_KEY_STORE);
    generator.initialize(spec);
    KeyPair keyPair = generator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
}
 
开发者ID:drakeet,项目名称:rebase-android,代码行数:29,代码来源:BlackBox.java

示例3: createSelfSignedCert

import java.security.KeyStore; //导入方法依赖的package包/类
private void createSelfSignedCert(File targetKeystore, String keyName,
    String keystorePassword) {
  if (targetKeystore.exists()) {
    throw new RuntimeException("Keystore already exists: " + targetKeystore);
  }

  try {
    KeyPair kp = generateKeyPair();

    X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(),
        kp.getPrivate());

    char[] password = keystorePassword.toCharArray();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(null, null);
    keystore.setCertificateEntry(keyName + "Cert", cert);
    keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] {cert});
    try (FileOutputStream fos = new FileOutputStream(targetKeystore)) {
      keystore.store(fos, password);
    }
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
开发者ID:apache,项目名称:calcite-avatica,代码行数:25,代码来源:SslDriverTest.java

示例4: createRequest

import java.security.KeyStore; //导入方法依赖的package包/类
/**
   * 创建Http/Https请求对象
   * @author Rocye
   * @param url 请求地址
   * @param method 请求方式:GET/POST
   * @param certPath 证书路径
   * @param certPass 证书密码
* @param useCert 是否需要证书
   * @return Https连接
   * @throws Exception 任何异常
   * @version 2017.11.14
   */
  private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{
      URL realUrl = new URL(url);
      HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();

      //设置证书
if(useCert){
	KeyStore clientStore = KeyStore.getInstance("PKCS12");
	InputStream inputStream = new FileInputStream(certPath);
	clientStore.load(inputStream, certPass.toCharArray());
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(clientStore, certPass.toCharArray());
	KeyManager[] kms = kmf.getKeyManagers();
	SSLContext sslContext = SSLContext.getInstance("TLSv1");
	sslContext.init(kms, null, new SecureRandom());
	connection.setSSLSocketFactory(sslContext.getSocketFactory());
}

      // 设置通用的请求属性
      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setConnectTimeout(this.connectTimeout);
      connection.setReadTimeout(this.readTimeout);
      if("POST".equals(method)){
          // 发送POST请求必须设置如下两行
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setUseCaches(false);   // 忽略缓存
          connection.setRequestMethod("POST");
      }
      return connection;
  }
 
开发者ID:rocye,项目名称:wx-idk,代码行数:44,代码来源:HttpsRequestTools.java

示例5: getTrustStore

import java.security.KeyStore; //导入方法依赖的package包/类
public KeyStore getTrustStore(DremioConfig config) throws GeneralSecurityException, IOException {
  String trustStorePath = getConfig(config, WEB_SSL_TRUSTSTORE);
  char[] trustStorePassword;
  if (trustStorePath == null) {
    // Check if auto-generated certificates are used
    Path path = Paths.get(config.getString(LOCAL_WRITE_PATH_STRING), TRUST_STORE_FILE);
    if (Files.notExists(path)) {
      return null;
    }

    trustStorePath = path.toString();
    trustStorePassword = UNSECURE_PASSWORD_CHARARRAY;
  } else {
    logger.info("Loading configured truststore at {}", trustStorePath);
    String password = getConfig(config, WEB_SSL_TRUSTSTORE_PASSWORD);
    trustStorePassword = password != null ? password.toCharArray() : null;
  }

  KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  try(InputStream stream = Files.newInputStream(Paths.get(trustStorePath))) {
    trustStore.load(stream, trustStorePassword);
  }
  return trustStore;
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:25,代码来源:HttpsConnectorGenerator.java

示例6: getKeystore

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

        KeyStore ks = null;
        try (FileInputStream fis = new FileInputStream(certLocation)) {
            ks = KeyStore.getInstance(PKCS12_KEYSTORE_TYPE, BouncyCastleProvider.PROVIDER_NAME);
            ks.load(fis, certPassword.toCharArray());

            if (aliasOrCN == null) {
                Enumeration<String> aliases = ks.aliases();
                String alias = aliases.nextElement();
                aliasOrCN = alias;
            }

        } catch (Exception e) {
            throw new ActionException(e);
        }
        return ks;
    }
 
开发者ID:Axway,项目名称:ats-framework,代码行数:19,代码来源:SMimePackageEncryptor.java

示例7: getKeyManagerFactory

import java.security.KeyStore; //导入方法依赖的package包/类
private static KeyManagerFactory getKeyManagerFactory() throws Exception {
  KeyStore ks = KeyStore.getInstance("JKS");
  ks.load(getKeyStoreInputStream(), PASSWORD);

  KeyManagerFactory kmf = KeyManagerFactory.getInstance(ALGORITHM);
  kmf.init(ks, PASSWORD);

  return kmf;
}
 
开发者ID:HubSpot,项目名称:NioSmtpClient,代码行数:10,代码来源:FakeTlsContext.java

示例8: getNotificationTlsContext

import java.security.KeyStore; //导入方法依赖的package包/类
public static SSLContext getNotificationTlsContext(Context c, Certificate serverCert){
    try {
        SSLContext tlsContext = SSLContext.getInstance(TLS_VERSIONS[0]);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("key", RsaHelper.getPrivateKey(c), "".toCharArray(),
                new Certificate[]{TlsHelper.getCertificate(c)});
        keyStore.setCertificateEntry("serverCert", serverCert);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        tlsContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
        return tlsContext;
    } catch (Exception e){
        Log.e("TlsHelper", "getNotificationTlsContext");
        Log.e("StackTrace", Log.getStackTraceString(e));
        return null;
    }
}
 
开发者ID:rootkiwi,项目名称:an2linuxclient,代码行数:25,代码来源:TlsHelper.java

示例9: loadTrustMaterial

import java.security.KeyStore; //导入方法依赖的package包/类
public SSLContextBuilder loadTrustMaterial(
        final File file,
        final char[] storePassword,
        final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    Args.notNull(file, "Truststore file");
    final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {
        trustStore.load(instream, storePassword);
    } finally {
        instream.close();
    }
    return loadTrustMaterial(trustStore, trustStrategy);
}
 
开发者ID:gusavila92,项目名称:java-android-websocket-client,代码行数:15,代码来源:SSLContextBuilder.java

示例10: setUpSSL

import java.security.KeyStore; //导入方法依赖的package包/类
public static void setUpSSL(Context context) {
        // set up keystore
        try (InputStream clientInput = context.getResources().openRawResource(R.raw.rdw_poc_mdl_client_ca);
             //InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ca)) {
             InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ssl)) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            //java.security.cert.Certificate clientCA = cf.generateCertificate(clientInput);

            // This part sends my cert to server
//            KeyStore clientStore = KeyStore.getInstance("PKCS12");
//            clientStore.load(clientInput, "password".toCharArray());
            //clientStore.setCertificateEntry("", clientCA);

//            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            keyManagerFactory.init(clientStore, null);

            // this part trusts a remote certificate
            java.security.cert.Certificate serverCA = cf.generateCertificate(serverInput);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore serverStore = KeyStore.getInstance("PKCS12");
            serverStore.load(null, null);
            serverStore.setCertificateEntry("", serverCA);
            tmf.init(serverStore);

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, tmf.getTrustManagers(), null);

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        } catch (Exception e) {
            Log.e("TLS", "Something went wrong", e);
        }
    }
 
开发者ID:mDL-ILP,项目名称:mDL-ILP,代码行数:34,代码来源:NetUtils.java

示例11: getKeyManagers

import java.security.KeyStore; //导入方法依赖的package包/类
private KeyManager[] getKeyManagers() {
    if (keystoreFilename != null && keystorePassword != null && keystoreType != null) {
        try {
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(keystoreType);
            loadKeystore(keystore, keystoreFilename, keystorePassword);
            keyManagerFactory.init(keystore, keystorePassword.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to load Keystore", e);
        }
    } else {
        return null;
    }
}
 
开发者ID:hortonworks,项目名称:nifi-android-s2s,代码行数:16,代码来源:SiteToSiteRemoteCluster.java

示例12: getTrustedSslContext

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile     the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType     the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final Resource trustStoreFile, final String trustStorePassword,
                                               final String trustStoreType) {
    try {

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (InputStream casStream = trustStoreFile.getInputStream()) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager(ALG_NAME_PKIX, casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager(ALG_NAME_PKIX, casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useProtocol("SSL").build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:42,代码来源:FileTrustStoreSslSocketFactory.java

示例13: removeAliasAndFiles

import java.security.KeyStore; //导入方法依赖的package包/类
private synchronized static void removeAliasAndFiles(Context context, String alias, String dataFileName, String ivFileName) {
	KeyStore keyStore;
	try {
		keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
		keyStore.load(null);
		keyStore.deleteEntry(alias);
		new File(getFilePath(context, dataFileName)).delete();
		new File(getFilePath(context, ivFileName)).delete();
	} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
		e.printStackTrace();
	}
}
 
开发者ID:TrustWallet,项目名称:trust-wallet-android,代码行数:13,代码来源:KS.java

示例14: main

import java.security.KeyStore; //导入方法依赖的package包/类
public static void main (String[] args) throws Exception {
    SecretKey key = new SecretKeySpec(new byte[8], "DES");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, passwd);

    try {
        // store the SecretKey
        ks.setKeyEntry("test_encrypt_key", key, passwd, null);
        throw new Exception("Should throw KeyStoreException when " +
            "storing SecretKey into JKS keystores");
    } catch (KeyStoreException kse) {
        // expected exception thrown; swallow
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:16,代码来源:TestJKSWithSecretKey.java

示例15: decryptData

import java.security.KeyStore; //导入方法依赖的package包/类
/**
 * Decrypt contents of File given path and
 * return a string representation of the decrypted data
 * @param encryptedDataFileName String representing file name
 * @return Decrypted string or null if decryption fails
 * @throws Exception related to decryption
 */
private String decryptData (final String encryptedDataFileName) throws Exception{
  String decryptedString;

  final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
  keyStore.load(null);
  final SecretKey key = (SecretKey) keyStore.getKey(ALIAS, null);

  final Cipher c = Cipher.getInstance(CIPHER_TYPE);

  final File file = new File(getFilePath(encryptedDataFileName));
  final int fileSize = (int)file.length();

  // Need to provide the GCMSpec used by the
  // encryption method when decrypting
  final File ivFile = new File(getFilePath(Constants.IV_FILE));
  final int ivFileSize =  (int) ivFile.length();
  final FileInputStream fis = new FileInputStream(getFilePath(Constants.IV_FILE));
  final byte [] iv = new byte[ivFileSize];

  int index = 0;
  int nextByte;
  while ((nextByte = fis.read()) != -1){
    iv[index] = (byte) nextByte;
    index++;
  }
  fis.close();

  GCMParameterSpec spec = new GCMParameterSpec(128, iv);
  Log.i(TAG, "Decrypted spec iv length " +  spec.getIV().length + " tag length = "+ spec.getTLen());
  c.init(Cipher.DECRYPT_MODE, key, spec);

   final CipherInputStream cipherInputStream =
      new CipherInputStream(new FileInputStream(getFilePath(encryptedDataFileName)),
          c);
  final byte[] fileContentBytes = new byte[fileSize];

  index = 0;
  while ((nextByte = cipherInputStream.read()) != -1) {
    fileContentBytes[index] = (byte) nextByte;
    index++;
  }
  cipherInputStream.close();

  decryptedString = new String(fileContentBytes, 0, index, Charsets.UTF_8);
  Log.v(TAG, "Decrypted string = " + decryptedString);

  return decryptedString;
}
 
开发者ID:Esri,项目名称:mapbook-android,代码行数:56,代码来源:CredentialCryptographer.java


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