我目前正在Android应用程序中存储RSA密钥,它将用于应用程序加密用户应用程序数据。
我生成密钥并将其保存为密钥目录中的文件,如下所示:
public RSA(char[] password) throws Exception
{
private static final String filePath = System.getProperty("user.dir") + "/keys/";
mCurrentPassword = password;
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
File possibleKeyFile = new File(filePath + "/" + keyAlias);
//FileInputStream keyFile = new FileInputStream(filePath + "/" + keyAlias);
if(!possibleKeyFile.exists()) //if keystore is empty, create a key
{
mCurrentCertificate = generateCert();
//Store the new keypair
ks.load(null, 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(keyAlias, pkEntry, protParam);
OutputStream os = new FileOutputStream(new File(filePath + "/" + keyAlias));
ks.store(os , password);
}
else
{
//retrieve keypair and assign it to mCurrentKeyPair
mCurrentRSAKeyPair = getKey(keyAlias, password);
}
}
当我在调试模式下检索我的android上的密钥库时,我收到一条错误,指出该文件不存在(无效目录)。我想知道如果存储路径设置为那么密钥实际存储在哪里?
检索密钥对的代码:
private static KeyPair getKey(String alias, char[] password) throws Exception
{
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream keyFile = new FileInputStream(filePath + "/" + alias);
ks.load(keyFile, password);
KeyStore.ProtectionParameter protParam =
new KeyStore.PasswordProtection(password);
KeyStore.PrivateKeyEntry privateKeyEntry =
(KeyStore.PrivateKeyEntry) ks.getEntry(alias, protParam);
RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
//get public key from private key
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec priv = kf.getKeySpec(privateKey, RSAPrivateKeySpec.class);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(priv.getModulus(), BigInteger.valueOf(65537));
PublicKey publicKey = kf.generatePublic(keySpec);
KeyPair kp = new KeyPair(publicKey, privateKey);
return kp;
}
答案 0 :(得分:0)
OutputStream os = new FileOutputStream(new File(filePath + "/" + keyAlias));
在执行此行之前,您应执行以下操作:
filePath.mkdirs();
目前,“密钥”目录可能不存在,并且您没有采取任何措施来确保它确实存在。
您还需要在存储密钥库后关闭输出流。您似乎也忽略了IOException
或FileNotFoundException
某处。