且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用java.security.KeyStore类存储和加载密钥

更新时间:2023-01-18 09:58:59

存储:

KeyStore ks = KeyStore.getInstance("JKS");
ks.setKeyEntry("keyAlias", key, passwordForKeyCharArray, certChain);
OutputStream writeStream = new FileOutputStream(filePathToStore);
ks.store(writeStream, keystorePasswordCharArray);
writeStream.close();

注意,certChain可能为null,除非您传递 PrivateKey

Note thet certChain might be null, unless you are passing PrivateKey

正在加载:

KeyStore ks = KeyStore.getInstance("JKS");
InputStream readStream = new FileInputStream(filePathToStore);
ks.load(readStream, keystorePasswordCharArray);
Key key = ks.getKey("keyAlias", passwordForKeyCharArray);
readStream.close();

阅读 javadocs

编辑:

请注意,如果要存储SecretKey或使用SunJCE提供程序的任何部分(Java Cryptography Extension),则需要将KeyStore类型设置为JCEKS。

Note that if you are storing a SecretKey or using any part of the SunJCE provider (Java Cryptography Extension), you will need to set your KeyStore type to JCEKS.

KeyStore ks = KeyStore.getInstance("JCEKS");

我很感激,如果你解释我如何在我的ssl / tls应用程序中使用它(sslserversocketfactory)我需要给它一个CA证书的路径

I'd appreciate if you explain How can i use this with my ssl/tls application (sslserversocketfactory) i need to give it the path of a CA certificate