如何使用 java.security.KeyStore 类存储和加载密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3027273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store and load keys using java.security.KeyStore class
提问by condinya
After creating secret keys, how do I store them using the Keystore class' methods and how do I load the keys?
创建密钥后,如何使用 Keystore 类的方法存储它们以及如何加载密钥?
采纳答案by Bozho
Storing:
储存:
KeyStore ks = KeyStore.getInstance("JKS");
ks.setKeyEntry("keyAlias", key, passwordForKeyCharArray, certChain);
OutputStream writeStream = new FileOutputStream(filePathToStore);
ks.store(writeStream, keystorePasswordCharArray);
writeStream.close();
Note thet certChain might be null, unless you are passing PrivateKey
请注意 certChain 可能为空,除非您通过 PrivateKey
Loading:
加载:
KeyStore ks = KeyStore.getInstance("JKS");
InputStream readStream = new FileInputStream(filePathToStore);
ks.load(readStream, keystorePasswordCharArray);
Key key = ks.getKey("keyAlias", passwordForKeyCharArray);
readStream.close();
Read the javadocs
阅读javadocs
EDIT:
编辑:
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.
请注意,如果您要存储 SecretKey 或使用 SunJCE 提供程序(Java 加密扩展)的任何部分,则需要将 KeyStore 类型设置为 JCEKS。
KeyStore ks = KeyStore.getInstance("JCEKS");
回答by neha
I had a situation where I didn't know the key alias name, but I knew there was only one key was there in the keystore. I used the following code to load the key (after loading the keystore as shown above):
我遇到过不知道密钥别名的情况,但我知道密钥库中只有一个密钥。我使用以下代码加载密钥(如上图加载密钥库后):
Enumeration<String> aliases = keyStore.aliases();
String alias = aliases.nextElement();
KeyStore.PrivateKeyEntry keyEnt = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
new KeyStore.PasswordProtection(keystorePass.toCharArray()));
PrivateKey privateKey = keyEnt.getPrivateKey();
I have added a post on my blogwith details of how to load the private key, public key and how to use them.