java类java.security.KeyStore的实例源码

CredentialCryptographer.java 文件源码 项目:mapbook-android 阅读 42 收藏 0 点赞 0 评论 0
/**
 * Create a new key in the Keystore
 */
private void createNewKey(){
  try {
    final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null);

    final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);

    // Build one key to be used for encrypting and decrypting the file
    keyGenerator.init(
        new KeyGenParameterSpec.Builder(ALIAS,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .build());
    keyGenerator.generateKey();
    Log.i(TAG, "Key created in Keystore");

  }catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException  kS){
    Log.e(TAG, kS.getMessage());
  }
}
ClientHelloRead.java 文件源码 项目:jdk8u-jdk 阅读 44 收藏 0 点赞 0 评论 0
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();
    }
}
AuthResourceTest.java 文件源码 项目:sample-acmegifts 阅读 43 收藏 0 点赞 0 评论 0
/**
 * Tests the JWT we get back from the auth service is valid. We test the JWT to make sure it was
 * signed correctly.
 *
 * <p>We do not validate other things, like the issued at time, expired time, etc.
 *
 * <p>The test case has access to the keystore that the server should have used to sign the JWT.
 */
@Test
public void testLoginJwtValidity() throws Exception {
  // Get the JWT from the auth service.
  Response response = processRequest(authServiceURL, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());
  String authHeader = response.getHeaderString("Authorization");

  // Open the keystore that the server should have used to sign the JWT.
  KeyStore ks = KeyStore.getInstance("JCEKS");
  InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
  char[] password = new String("secret").toCharArray();
  ks.load(ksStream, password);
  java.security.cert.Certificate cert = ks.getCertificate("default");
  PublicKey publicKey = cert.getPublicKey();

  // Make sure it's valid.  Use the server's public key to check.
  new JWTVerifier().validateJWT(authHeader, publicKey);
}
HTTPSPKCSCoder.java 文件源码 项目:iBase4J-Common 阅读 44 收藏 0 点赞 0 评论 0
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
        throws Exception {
    // 实例化密钥库
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    // 获得密钥库
    KeyStore keyStore = getKeyStore(keyStorePath, password);
    // 初始化密钥工厂
    keyManagerFactory.init(keyStore, password.toCharArray());
    // 实例化信任库
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    // 获得信任库
    KeyStore trustStore = getKeyStore(trustStorePath, password);
    // 初始化信任库
    trustManagerFactory.init(trustStore);
    // 实例化SSL上下文
    SSLContext ctx = SSLContext.getInstance(PROTOCOL);
    // 初始化SSL上下文
    ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    // 获得SSLSocketFactory
    return ctx.getSocketFactory();

}
SecurityUtils.java 文件源码 项目:RISE-V2G 阅读 42 收藏 0 点赞 0 评论 0
/**
 * Returns a standard keystore which holds the respective credentials (private key and certificate chain).
 * 
 * @param keyStoreIS The input stream of the keystore
 * @param keyStorePassword The password which protects the keystore
 * @param keyStoreType The type of the keystore, either "jks" or "pkcs12"
 * @return The respective keystore
 */
private static KeyStore getKeyStore(InputStream keyStoreIS, String keyStorePassword, String keyStoreType) {
    KeyStore keyStore = null;

    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreIS, keyStorePassword.toCharArray());
        keyStoreIS.close();
        return keyStore;
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | 
            IOException | NullPointerException e) {
        getLogger().error(e.getClass().getSimpleName() + " occurred while trying to load keystore", e);
    } 

    return null;
}
DefaultX509TrustManager.java 文件源码 项目:cyberduck 阅读 48 收藏 0 点赞 0 评论 0
public DefaultX509TrustManager init() throws IOException {
    try {
        final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init(KeyStore.getInstance(KeyStore.getDefaultType()));
        final TrustManager[] trustmanagers = factory.getTrustManagers();
        if(trustmanagers.length == 0) {
            throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
        }
        system = (javax.net.ssl.X509TrustManager) trustmanagers[0];
    }
    catch(NoSuchAlgorithmException | KeyStoreException e) {
        log.error(String.format("Initialization of trust store failed. %s", e.getMessage()));
        throw new IOException(e);
    }
    return this;
}
HttpsRequestTools.java 文件源码 项目:wx-idk 阅读 43 收藏 0 点赞 0 评论 0
/**
   * 创建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;
  }
PKIXParameters.java 文件源码 项目:OpenJSharp 阅读 38 收藏 0 点赞 0 评论 0
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
ConvertP12Test.java 文件源码 项目:jdk8u-jdk 阅读 33 收藏 0 点赞 0 评论 0
private void compareKeyStore(KeyStore a, KeyStore b, String inKeyPass,
        String outKeyPass, int keyStoreSize) throws Exception {
    if (a.size() != keyStoreSize || b.size() != keyStoreSize) {
        throw new RuntimeException("size not match or size not equal to "
                + keyStoreSize);
    }

    Enumeration<String> eA = a.aliases();
    while (eA.hasMoreElements()) {
        String aliasA = eA.nextElement();

        if (!b.containsAlias(aliasA)) {
            throw new RuntimeException("alias not match for alias:"
                    + aliasA);
        }

        compareKeyEntry(a, b, inKeyPass, outKeyPass, aliasA);
    }
}
Main.java 文件源码 项目:jdk8u-jdk 阅读 47 收藏 0 点赞 0 评论 0
private static String verifyCRL(KeyStore ks, CRL crl)
        throws Exception {
    X509CRLImpl xcrl = (X509CRLImpl)crl;
    X500Principal issuer = xcrl.getIssuerX500Principal();
    for (String s: e2i(ks.aliases())) {
        Certificate cert = ks.getCertificate(s);
        if (cert instanceof X509Certificate) {
            X509Certificate xcert = (X509Certificate)cert;
            if (xcert.getSubjectX500Principal().equals(issuer)) {
                try {
                    ((X509CRLImpl)crl).verify(cert.getPublicKey());
                    return s;
                } catch (Exception e) {
                }
            }
        }
    }
    return null;
}
FingerprintUiHelper.java 文件源码 项目:MakiLite 阅读 48 收藏 0 点赞 0 评论 0
/**
 * Initialize the {@link Cipher} instance with the created key in the {@link #createKey()}
 * method.
 *
 * @return {@code true} if initialization is successful, {@code false} if the lock screen has
 * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
 * the key was generated.
 */
private boolean initCipher() {
    try {
        if (mKeyStore == null) {
            mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        }
        createKey();
        mKeyStore.load(null);
        SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
        mCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        mCipher.init(Cipher.ENCRYPT_MODE, key);
        return true;
    } catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException e) {
        return false;
    }
}
Main.java 文件源码 项目:OpenJSharp 阅读 44 收藏 0 点赞 0 评论 0
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise.
 */
private static Certificate getTrustedSigner(Certificate cert, KeyStore ks)
        throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return cert;
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return trustedCert;
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
NanoHTTPD.java 文件源码 项目:webtrekk-android-sdk 阅读 47 收藏 0 点赞 0 评论 0
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase
 */
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);

        if (keystoreStream == null) {
            throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
        }

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);
        return makeSSLSocketFactory(keystore, keyManagerFactory);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
SSLManager.java 文件源码 项目:zabbkit-android 阅读 50 收藏 0 点赞 0 评论 0
public void dumpTrustedCerts() {
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory
                .getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
        StringBuffer buff = new StringBuffer();
        for (X509Certificate cert : xtm.getAcceptedIssuers()) {
            String certStr = "S:" + cert.getSubjectDN().getName() + "\nI:"
                    + cert.getIssuerDN().getName();
            Log.d(TAG, certStr);
            buff.append(certStr + "\n\n");
        }
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
TrustStoreController.java 文件源码 项目:AgentWorkbench 阅读 38 收藏 0 点赞 0 评论 0
/**
 * This Initializes the TrustStoreController.
 */
public TrustStoreController(Dialog ownerDialog, File trustStoreFile, String trustStorePassword, boolean edit) {
    this.ownerDialog = ownerDialog;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        if (trustStoreFile != null && trustStorePassword != null) {
            if(edit){
                openTrustStore(trustStoreFile, trustStorePassword);
            } else {
                createTrustStore(trustStoreFile, trustStorePassword);
            }
        }
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
}
KeyToolTest.java 文件源码 项目:jdk8u-jdk 阅读 48 收藏 0 点赞 0 评论 0
void sqeImportTest() throws Exception {
    KeyStore ks;
    remove("x.jks");
    testOK("", "-keystore x.jks -storepass changeit -keypass changeit -genkeypair -dname CN=olala");
    testOK("", "-keystore x.jks -storepass changeit -exportcert -file x.jks.p1.cert");
    /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey");
    testOK("", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert -noprompt");
    /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey");
    testOK("yes\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert");
    ks = loadStore("x.jks", "changeit", "JKS");
    assertTrue(ks.containsAlias("mykey"), "imported");
    /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey");
    testOK("\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert");
    ks = loadStore("x.jks", "changeit", "JKS");
    assertTrue(!ks.containsAlias("mykey"), "imported");
    testOK("no\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert");
    ks = loadStore("x.jks", "changeit", "JKS");
    assertTrue(!ks.containsAlias("mykey"), "imported");
    testFail("no\n", "-keystore x.jks -storepass changeit -importcert -file nonexist");
    testFail("no\n", "-keystore x.jks -storepass changeit -importcert -file x.jks");
    remove("x.jks");
}
KeyStoreHelper.java 文件源码 项目:CacheManage 阅读 46 收藏 0 点赞 0 评论 0
/**
 * JBMR2+ If Key with the default alias exists, returns true, else false.
 * on pre-JBMR2 returns true always.
 */
public static boolean isSigningKey(String alias) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        try {
            KeyStore keyStore =
                    KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
            keyStore.load(null);
            return keyStore.containsAlias(alias);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            return false;
        }
    } else {
        return false;
    }
}
ApiHttpClient.java 文件源码 项目:OSchina_resources_android 阅读 40 收藏 0 点赞 0 评论 0
private static void initSSL(AsyncHttpClient client) {
    try {
        /// We initialize a default Keystore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // We load the KeyStore
        trustStore.load(null, null);
        // We initialize a new SSLSocketFacrory
        MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
        // We set that all host names are allowed in the socket factory
        socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        // We set the SSL Factory
        client.setSSLSocketFactory(socketFactory);
        // We initialize a GET http request
    } catch (Exception e) {
        e.printStackTrace();
    }
}
PKCSAuthInit.java 文件源码 项目:monarch 阅读 37 收藏 0 点赞 0 评论 0
@Override
public Properties getCredentials(final Properties securityProperties,
    final DistributedMember server, final boolean isPeer) throws AuthenticationFailedException {
  final String keyStorePath = securityProperties.getProperty(KEYSTORE_FILE_PATH);
  if (keyStorePath == null) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: key-store file path property [" + KEYSTORE_FILE_PATH + "] not set.");
  }

  final String alias = securityProperties.getProperty(KEYSTORE_ALIAS);
  if (alias == null) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: key alias name property [" + KEYSTORE_ALIAS + "] not set.");
  }

  final String keyStorePass = securityProperties.getProperty(KEYSTORE_PASSWORD);

  try {
    final KeyStore ks = KeyStore.getInstance("PKCS12");
    final char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
    final FileInputStream certificatefile = new FileInputStream(keyStorePath);

    try {
      ks.load(certificatefile, passPhrase);
    } finally {
      certificatefile.close();
    }

    final Key key = ks.getKey(alias, passPhrase);

    if (key instanceof PrivateKey) {
      final PrivateKey privKey = (PrivateKey) key;
      final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
      final Signature sig = Signature.getInstance(cert.getSigAlgName());

      sig.initSign(privKey);
      sig.update(alias.getBytes("UTF-8"));
      final byte[] signatureBytes = sig.sign();

      final Properties newprops = new Properties();
      newprops.put(KEYSTORE_ALIAS, alias);
      newprops.put(SIGNATURE_DATA, signatureBytes);
      return newprops;

    } else {
      throw new AuthenticationFailedException(
          "PKCSAuthInit: " + "Failed to load private key from the given file: " + keyStorePath);
    }

  } catch (Exception ex) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: Exception while getting credentials: " + ex, ex);
  }
}
SSLUtil.java 文件源码 项目:FastLib 阅读 42 收藏 0 点赞 0 评论 0
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        Log.e("ssl", e.getMessage());
    }
    return null;
}
JSSESocketFactory.java 文件源码 项目:apache-tomcat-7.0.73-with-comment 阅读 42 收藏 0 点赞 0 评论 0
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType,
                                      String keystoreProvider,
                                      String algorithm,
                                      String keyAlias)
            throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(
                sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
        keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        String alias = keyAlias;
        if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
        }
    }

    return kms;
}
HTTPSPKCSCoder.java 文件源码 项目:automat 阅读 41 收藏 0 点赞 0 评论 0
/**
 * 获得KeyStore
 * 
 * @param keyStorePath 密钥库路径
 * @param password 密码
 * @return KeyStore 密钥库
 * @throws Exception
 */
private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception {
    // 实例化密钥库
    KeyStore ks = KeyStore.getInstance("PKCS12");
    // KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    // 获得密钥库文件流
    FileInputStream is = new FileInputStream(keyStorePath);
    // 加载密钥库
    ks.load(is, password.toCharArray());
    // 关闭密钥库文件流
    is.close();
    return ks;
}
MetadataStoreLoadTest.java 文件源码 项目:jdk8u-jdk 阅读 39 收藏 0 点赞 0 评论 0
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
KeyStoreFactory.java 文件源码 项目:neoscada 阅读 40 收藏 0 点赞 0 评论 0
/**
 * Creates a new {@link KeyStore}. This method will be called
 * by the base class when Spring creates a bean using this FactoryBean.
 *
 * @return a new {@link KeyStore} instance.
 */
public KeyStore newInstance() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
        CertificateException, IOException {
    if (data == null) {
        throw new IllegalStateException("data property is not set.");
    }

    KeyStore ks;
    if (provider == null) {
        ks = KeyStore.getInstance(type);
    } else {
        ks = KeyStore.getInstance(type, provider);
    }

    InputStream is = new ByteArrayInputStream(data);
    try {
        ks.load(is, password);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
            // Do nothing
        }
    }

    return ks;
}
SSLContextBuilder.java 文件源码 项目:lighthouse 阅读 43 收藏 0 点赞 0 评论 0
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);
}
MySSLSocketFactory.java 文件源码 项目:Mobike 阅读 42 收藏 0 点赞 0 评论 0
/**
 * Gets getUrl Default KeyStore
 *
 * @return KeyStore
 */
public static KeyStore getKeystore() {
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return trustStore;
}
KS.java 文件源码 项目:trust-wallet-android 阅读 39 收藏 0 点赞 0 评论 0
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();
    }
}
KeyStoreProvider.java 文件源码 项目:q-mail 阅读 50 收藏 0 点赞 0 评论 0
public X509Certificate getServerCertificate() {
    try {
        KeyStore keyStore = loadKeyStore();
        return (X509Certificate) keyStore.getCertificate(SERVER_CERTIFICATE_ALIAS);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
}
NanoHTTPD.java 文件源码 项目:webtrekk-android-sdk 阅读 46 收藏 0 点赞 0 评论 0
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
 * loaded KeyManagerFactory. These objects must properly loaded/initialized
 * by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
    try {
        return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
HTTPSCoder.java 文件源码 项目:mumu-core 阅读 57 收藏 0 点赞 0 评论 0
/**
 * 获得KeyStore
 * 
 * @param keyStorePath 密钥库路径
 * @param password 密码
 * @return KeyStore 密钥库
 * @throws Exception
 */
private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception {
    // 实例化密钥库
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    // 获得密钥库文件流
    FileInputStream is = new FileInputStream(keyStorePath);
    // 加载密钥库
    ks.load(is, password.toCharArray());
    // 关闭密钥库文件流
    is.close();
    return ks;
}


问题


面经


文章

微信
公众号

扫码关注公众号