我正在使用android上的Rsa加密/解密应用程序。我创建并将我的公钥/私钥保存到sharedpreferences.I我正在阅读它们并使用此代码块进行加密/解密:
public String RSADecrypt(byte[] encryptedBytes) throws NoSuchAlgorithmException, NoSuchPaddingException,InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, UnsupportedEncodingException {
privateKey = getPrivateKey();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(encryptedBytes);
return new String(cipherData,"UTF-16BE");
}
public String RSAEncrypt(String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, UnsupportedEncodingException {
publicKey = getPublicKey();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(plain.getBytes());
return new String(cipherData,"UTF-16BE");
}
现在,例如我正在尝试加密“BAHADIR”,它写入EditText无意义的单词。我使用了“UTF-8”,“UTF-16”,“UTF-16LE”,“UTF16BE”和“ISO-8859-1”,但每当我再次得到无意义的词语时,不一样,但所有这些都毫无意义。我哪里错了,你能帮助我吗?谢谢。
答案 0 :(得分:0)
您不应将二进制数据转换为String。例如,如果您希望将其作为可打印的字符串,则可以使用Base64编码对其进行编码。
尝试以下方法:
import android.util.Base64
...
byte[] cipherData = cipher.doFinal(encryptedBytes);
String cipherString = Base64.encodeBytes(cipherData);