KeyStore.getKey()返回null

时间:2018-01-18 16:03:58

标签: java encryption

我使用keytool使用此命令生成了一个密钥库:

keytool -genkey -alias serverprivate -keystore serverprivate.jks -storetype JKS -keyalg RSA -sigalg SHA256withRSA -keysize 2048 -storepass doyouknowdewey

密钥传递和存储传递是相同的。然后我提取公钥并将其插入到自己的密钥库中:

keytool -export -alias serverprivate -keystore serverprivate.jks -file temp.key -storepass doyouknowdewey
keytool -import -noprompt -alias serverpublic -keystore serverpublic.jks -file temp.key -storepass public

现在我在java中使用密钥库创建一个InputStream并创建一个KeyStore对象:

InputStream is = getClass().getResourceAsStream("keys/serverprivate.jks");
KeyStore serverPrivate = KeyStore.getInstance("JKS");
serverPrivate.load(is, "doyouknowdewey".toCharArray());

我提取密钥以生成密码实例,因此可以加密和解密文本:

Key key = serverPrivate.getKey("serverprivate", "douyouknowdewey".toCharArray());

一切正常,我可以使用私钥加密数据。但是,如果我尝试使用公钥进行decrpyting / encrypting,Key对象为null:

InputStream is = getClass().getResourceAsStream("keys/serverpublic.jks");
KeyStore serverPublic = KeyStore.getInstance("JKS");
serverPublic.load(is, "public".toCharArray());
Key key = serverPrivate.getKey("serverpublic", "public".toCharArray());
if(key == null) {
    System.err.println("Key is null");
} 
//returns null

那我该怎么做呢?

编辑:

显然,serverpublic不是密钥,而是证书。我通过运行serverPublic.isKeyEntry("serverpublic");找到了,它返回false,而serverPublic.isCertificateEntry("serverpublic");返回true。所以我把代码更改为:

InputStream is = getClass().getResourceAsStream("keys/serverpublic.jks");
KeyStore serverPublic = KeyStore.getInstance("JKS");
serverPublic.load(is, "public".toCharArray());
Certificate cert = serverPrivate.getCertificate("serverpublic");
if(cert == null) {
    System.err.println("Key is null");
} 

这不再返回null。但是当我运行它时,cipher.init仍会抛出一个nullpointer异常:

Cipher cipher;
cipher.init(Cipher.ENCRYPT_MODE, cert);

1 个答案:

答案 0 :(得分:1)

serverpublic不是密钥,而是证书。我必须使用

加载它
Certificate cert = serverPrivate.getCertificate("serverpublic");

然后致电

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, cert);