Android KeyStore 不保存 RSA 密钥
Android KeyStore not saving RSA key
我正在使用 android 密钥库 api 来存储 RSA 密钥对。
当我 运行 我的 android 处于调试模式时,它显示密钥对和证书字节已存储在密钥库中,但是当我重新加载调试器并尝试检索密钥时,密钥库似乎是空的。
我希望能够通过别名检索密钥。我下面的代码显示了如何创建和存储密钥对。
public RSA(char[] password) throws Exception {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
Enumeration<String> aliases = ks.aliases();
if(!aliases.hasMoreElements())
{
mCurrentCertificate = generateCert();
//Store the new keypair
FileInputStream fs = null;
ks.load(fs, password);
KeyStore.ProtectionParameter protParam =
new KeyStore.PasswordProtection(password);
java.security.cert.Certificate[] myCert =
new java.security.cert.Certificate[] { (java.security.cert.Certificate) mCurrentCertificate};
KeyStore.PrivateKeyEntry pkEntry =
new KeyStore.PrivateKeyEntry(mCurrentRSAKeyPair.getPrivate(),
myCert);
ks.setEntry("MyKey2", pkEntry, protParam);
for(int i = 0; i < ks.size(); i++)
{
//MyKey is the previous key stored, MyKey2 is the next one
System.out.println(ks.getCertificate("MyKey"));
}
}
}
使用您的代码,您可以在文件系统中创建一个密钥库(缺少 ks.store(fileOutputStream, password);
,但是 Android Keystore System 有一个特定的 API 来生成和使用密钥
在此 中,您有一个生成和加载 RSA 密钥的示例
我正在使用 android 密钥库 api 来存储 RSA 密钥对。
当我 运行 我的 android 处于调试模式时,它显示密钥对和证书字节已存储在密钥库中,但是当我重新加载调试器并尝试检索密钥时,密钥库似乎是空的。
我希望能够通过别名检索密钥。我下面的代码显示了如何创建和存储密钥对。
public RSA(char[] password) throws Exception {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
Enumeration<String> aliases = ks.aliases();
if(!aliases.hasMoreElements())
{
mCurrentCertificate = generateCert();
//Store the new keypair
FileInputStream fs = null;
ks.load(fs, password);
KeyStore.ProtectionParameter protParam =
new KeyStore.PasswordProtection(password);
java.security.cert.Certificate[] myCert =
new java.security.cert.Certificate[] { (java.security.cert.Certificate) mCurrentCertificate};
KeyStore.PrivateKeyEntry pkEntry =
new KeyStore.PrivateKeyEntry(mCurrentRSAKeyPair.getPrivate(),
myCert);
ks.setEntry("MyKey2", pkEntry, protParam);
for(int i = 0; i < ks.size(); i++)
{
//MyKey is the previous key stored, MyKey2 is the next one
System.out.println(ks.getCertificate("MyKey"));
}
}
}
使用您的代码,您可以在文件系统中创建一个密钥库(缺少 ks.store(fileOutputStream, password);
,但是 Android Keystore System 有一个特定的 API 来生成和使用密钥
在此