我在我的应用程序中使用 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 时,我不知道如何将其转换为 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;
}
你有什么想法吗? 非常感谢
最佳答案
要将 publicK(String) 转换为公钥,请执行以下操作:
byte[] keyBytes = Base64.decode(publicK.getBytes("utf-8"));
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(spec);
要将 privateK(String) 转换为私钥,请执行以下操作:
byte[] keyBytes = Base64.decode(privateK.getBytes("utf-8"));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priv = fact.generatePrivate(keySpec);
关于java - Java RSA 中来自字符串的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22900570/