2017-03-03 83 views
1

我正在使用android密钥库api来存储RSA密钥对。Android KeyStore未保存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")); 
     } 
    } 
} 

回答

0

与您的代码,你可以创建文件系统密钥库(它缺少ks.store(fileOutputStream, password);,但Android Keystore System有一个特定的API生成和使用按键

在这个answer你有一个例子产生并加载RSA密钥