2017-03-09 124 views
0

我目前在我的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

什么是filePath设置为?这就是你存储密钥到 – dweebo

回答

0
OutputStream os = new FileOutputStream(new File(filePath + "/" + keyAlias)); 

在你执行这条线,你应该执行这一个:

filePath.mkdirs(); 

目前,它有可能是目录“键”没有按”并不存在,而且你没有做任何事情来确保它的确存在。

您还需要在存储密钥库之后关闭输出流。看起来你也忽略了某个地方的IOExceptionFileNotFoundException

+0

嗨,路径已经创建,并且它在检索密钥库而不是创建密钥库方面失败。欢呼 – James

+0

所以'别名'的值与您创建它时的值不同。当然,根本不需要'alias'作为文件名的一部分,因为密钥库可以包含多个别名。您可以使用固定的文件名,例如'System.getProperty(“user.dir”)+“/.keystore”'。当然,如果您已经拥有密钥对和证书,您为什么还需要密钥库文件? – EJP

+0

嗨,我需要密钥库,以便每次重新加载应用程序时我都可以保留相同的密钥对和证书,而不是每次擦除数据并重新生成它 – James

相关问题