java密钥库和密码设置 [英] java keystore and password settings

查看:187
本文介绍了java密钥库和密码设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java密钥库和keytool上有以下问题。我假设密钥库可能有多个证书。正如我所尝试的那样,通过keytool我可以创建一个密钥库,并且要访问这个密钥库,我必须设置密码。另外,要访问每个证书条目,我必须设置密码。是否必须为密钥库和条目使用相同的密码?如果没有(我认为这是合理的假设)为什么是以下代码:

I have the following question on java keystores and keytool. I assume that a keystore may have more than 1 certificates. As I have tried, via keytool I can create a keystore, and to access this keystore I have to set a password. Also to access each certificate entry I have to set a password. Is it mandatory to have the same password for the keystore and the entries? If not (and I think that it is reasonable to assume so) why is the following code:

char[] pwd = new char[]{'s','e','c','r','e','t'};
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream("myPersonal.keystore"), pwd);
kmf.init(ks, pwd);//fails here with exception

给了我以下异常?

Exception in thread "main" java.security.UnrecoverableKeyException: Cannot recover key
    at sun.security.provider.KeyProtector.recover(Unknown Source)
    at sun.security.provider.JavaKeyStore.engineGetKey(Unknown Source)
    at sun.security.provider.JavaKeyStore$JKS.engineGetKey(Unknown Source)
    at java.security.KeyStore.getKey(Unknown Source)

secret 是访问我通过keytool创建的密钥库 myPersonal.keystore 的密码。其中有2个条目,用于证书,1个DSA和1个RSA。每个密码库都有不同的密码(和彼此)。现在代码是正确的,因为如果我使用一个密钥库,其中一个证书条目具有与密钥库相同的密码,则没有异常且程序运行正常。

secret is the password to access the keystore myPersonal.keystore which I created via keytool. There are 2 entries in it, for certificates, 1 DSA and 1 RSA. Each has a different password with keystore (and each other). Now the code is correct, because if I use a keystore with a single certificate entry having the same password as the keystore there is no exception and the program runs fine.

所以这里有什么问题?我不应该有不同的密码?我不应该有很多证书?或者是什么?

So what is the problem here? I should not have different passwords? I should not have many certificates? Or what?

推荐答案

根据API的规定,KeyManagerFactory.init方法接受用于从中检索密钥的密​​码。密钥库。由于只有一个密码参数,因此期望所有密钥的密码相同。如果其中一个密钥使用了不同的密码,那么您将看到由于该特定密钥库条目的密码不正确而看到的错误。

As specified by the API, the KeyManagerFactory.init method takes in the password used to retrieve the keys from the keystore. Since there is only one password parameter, it is expecting that the password for all the keys are identical. If a different password is used for one of the keys, then you get the error you saw as the password is incorrect for that particular keystore entry.

最简单的解决方案是对密钥库中的所有条目使用相同的密码。如果您设置为每个条目维护不同的密码,那么您可能需要考虑构建自己的自定义安全元素,例如KeyManager。

The simplest solution for you would be to use the same password for all the entries in the keystore. If you are set on maintaining different passwords for each entry, then you may have to look into building your own custom security elements, e.g., KeyManager.

这篇关于java密钥库和密码设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆