我在我的應用程序中使用RSA加密技術。要存儲生成的公鑰,我將其轉換爲字符串,然後將其保存在數據庫中。Java中的字符串的密鑰RSA
Key publicKey=null;
Key privateKey=null;
KeyPair keyPair=RsaCrypto.getKeyPairRSA(1024);
publicKey=keyPair.getPublic();
privateKey=keyPair.getPrivate();
String publicK=Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT);
String privateK=Base64.encodeToString(privateKey.getEncoded(), Base64.DEFAULT);
我保存字符串publicK
和privateK
。 我的問題是,當我想用RSA加密/解密文本並使用我保存的字符串格式的密鑰時,我不知道如何將其轉換爲Key
。
public static String encrypt(Key publicKey, String inputText){
byte[]encodedBytes=null;
String encryptedText="";
try {
Cipher cipher=Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encodedBytes=cipher.doFinal(inputText.getBytes());
} catch (Exception e) {Log.e("Error", "RSA encryption error"); }
encryptedText=Base64.encodeToString(encodedBytes, Base64.DEFAULT);
return encryptedText;
}
你有什麼想法嗎? 非常感謝
請,請,請不要將未加密的私鑰存儲在數據庫中。如果您必須存儲稱爲託管的私鑰,並且您應該使用只有您的應用程序已知的對稱密鑰對它們進行加密。 – KyleM
謝謝,是的,我正在考慮這個問題。您能否給我一個建議,在應用程序中存儲密鑰的最佳方式是什麼?謝謝 – rgreso
使用受密碼保護的Java密鑰庫。查找Java keytool ... – KyleM