我正在编写一个在Android中使用RSA的程序。我有以下问题: 我收到RSA密钥:Android中的RSA加密
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
使用加密功能加密测试字符串:
String test ="test";
byte[] testbytes = test.getBytes();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(testbytes);
String s = new String(cipherData);
Log.d("testbytes after encryption",s);
在解密功能,我正在对数据进行解密回去取原始字符串
Cipher cipher2 = Cipher.getInstance("RSA");
cipher2.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainData = cipher.doFinal(cipherData);
String p = new String(plainData);
Log.d("decrypted data is:",p);
打印在日志中的'p'中的数据与原始字符串“test”不匹配。我在哪里错了?
那么是什么在日志中打印出来?如果你有不匹配的密钥或乱码,你会得到一个异常,而不是一个错误的答案。 –
另外请注意''cipherData'将是一个随机的二进制字符串,所以通过使用原始字节('String s = new String(cipherData);')将它转换为一个字符串可能会给你奇怪的结果。 –