java - Android的KeyStore getKey返回null

标签 java android encryption rsa

我使用这个小 fragment 在 Android 的 keystore 中存储 key 对:

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
Certificate[] cert = new Certificate[1];
cert[0] = getCertificate(kp);
ks.setKeyEntry(PRIVATE_KEY_TAG, kp.getPrivate(), null, cert);
ks.setKeyEntry(PUBLIC_KEY_TAG, kp.getPublic(), null, cert);

但是当我使用 ks.getKey(PUBLIC_KEY_TAG, null).getEncoded() 从 KeyStore 获取 key 时,出现此异常:

Attempt to invoke interface method Key.getEncoded() on a null object

当我尝试通过密码加密字符串时,我得到:

Unknow key type passed to RSA

知道为什么这个 KeyStore 会引起问题吗? 谢谢。

最佳答案

您可以retrieve the public key from the certificate instead 。 key 存储可用于存储您自己持有的私钥/证书,或另一个实体的可信证书。 Java(和Android) key 存储主要针对基于X5.09的PKI。将公钥与证书一起存储没有意义,公钥已经包含在证书中。

所以尝试:

ks.getCertificate(PRIVATE_KEY_TAG).getPublicKey().getEncoded();

关于java - Android的KeyStore getKey返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27582847/

相关文章:

java - 生成外部编辑器 - 这是如何工作的?

java - 将单元格颜色更改为特定定义的颜色

java - 如何在 Java 中显示具有整数值的 Set 中的元素

java - 线程中的异常 "main"java.net.UnknownHostException :

java - 如何消除E Zygote?

php - 加密和解密字符串 - PHP

ssl - 在服务器 key 交换中使用私钥计算签名

android - 识别加速度计模式的神经网络

android - 如何更改滚动 Activity 标题的大小?

java - 为什么这一行在java中不起作用?