将字符串转换为字节以进行 "RSA" 加密时出现问题(Java)
Troubles converting String to Byte for "RSA" encryption( Java)
我想创建几个 java 函数以添加到 android studio application.The 这些函数的目的是开始能够使用 RSA 加密发送加密消息。
我首先生成两个密钥。然后我使用 public 加密我的消息并且它有效。然后,我将加密消息从 byte[] 转换为 String(),因为我想通过 SMS 发送消息。
所有这些部分都有效。然后我尝试重用我应该在 SMS 中收到的 SMS 但它没有 work.I 出现以下错误 :
"javax.crypto.BadPaddingException: Decryption error" <br/>
在这一行中:
"descryptedData = cipher.doFinal(decrypt); " //(参见下面的代码)
我使用 .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();
}
我想错误来自将字符串转换为字节以及将字节转换为字符串,但我不知道如何解决。有人有想法吗?
通常人们使用 base64 encoder/decoder 之类的东西来转换字节数组 to/from 字符串,因为简单转换为 UTF-8 会丢失一些数据,没有人能保证随机字节序列具有正确的表示作为 UTF-8 字符串。
例如,查看 android 的示例,这是一个有点不同的问题,但我相信您需要的答案完全相同。
我想创建几个 java 函数以添加到 android studio application.The 这些函数的目的是开始能够使用 RSA 加密发送加密消息。
我首先生成两个密钥。然后我使用 public 加密我的消息并且它有效。然后,我将加密消息从 byte[] 转换为 String(),因为我想通过 SMS 发送消息。 所有这些部分都有效。然后我尝试重用我应该在 SMS 中收到的 SMS 但它没有 work.I 出现以下错误 :
"javax.crypto.BadPaddingException: Decryption error" <br/>
在这一行中:
"descryptedData = cipher.doFinal(decrypt); " //(参见下面的代码)
我使用 .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();
}
我想错误来自将字符串转换为字节以及将字节转换为字符串,但我不知道如何解决。有人有想法吗?
通常人们使用 base64 encoder/decoder 之类的东西来转换字节数组 to/from 字符串,因为简单转换为 UTF-8 会丢失一些数据,没有人能保证随机字节序列具有正确的表示作为 UTF-8 字符串。
例如,查看 android 的示例,这是一个有点不同的问题,但我相信您需要的答案完全相同。