【发布时间】:2017-11-12 12:50:03
【问题描述】:
我想创建几个 java 函数来添加到一个 android studio 应用程序中。这些函数的目的是开始能够使用 RSA 加密发送加密消息。
我首先生成两个密钥。然后我使用公共的加密我的消息,它可以工作。然后,我将加密消息从 byte[] 转换为 String(),因为我想通过 SMS 发送消息。 所有这些部分都有效。然后我尝试重用我应该在短信中收到的短信,但它不起作用。我收到以下错误:
"javax.crypto.BadPaddingException: Decryption error" <br/>
在这一行:
"descryptedData = cipher.doFinal(decrypt); " // (cf code below)
我使用 .toString() 函数将加密的消息从字节转换为字符串。如果我跳过从字节转换为字符串以发送 SMS 以及从字符串转换为字节以解密数据的部分,它会完美运行。
这是您可能感兴趣的代码部分:
PrivateKey privateKey = null;
privateKey = appMob.getPrivKey(keys[1]); //return the privatekey
System.out.println("\n--- Decryption started--- \n");
byte[] descryptedData = null;
try{
byte[] decrypt = smsWithCryptedData.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE,privateKey);
descryptedData = cipher.doFinal(decrypt);
String smsFinal = new String(descryptedData);
System.out.println("decrypt \n smsFinal");
}catch(Exception e)
{
e.printStackTrace();
}
我想错误来自将字符串转换为字节和字节转换为字符串,但我不知道如何解决它。有人有想法吗?
【问题讨论】:
-
"我使用 ".toString()" 函数将加密的消息从字节转换为字符串" - 这是你不应该做的。
String不是任意二进制数据的容器。 -
有人知道我可以用什么解决方案以可重用的方式将字节数据转换为字符串吗?
-
您没有阅读我链接到的答案吗?
-
是的,我做到了,我终于找到了解决方案。通过将字节转换为 Biginteger(加密期间使用的类型),然后将 BigInteger 转换为 String。它现在可以工作了 :) 谢谢你告诉我我不能直接做到这一点!
标签: java encryption cryptography rsa