public static String encryptByPublicKey(byte[] data, String key)
throws Exception {
byte[] keyBytes = decryptBASE64(key);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return new String(cipher.doFinal(data));
}
I have a public key, like MFWww.........EAAQ==
. When I pass the string to that argument, the encrypted message is some unknown characters. Therefore I suspect I should do something on the key before passing it to the function. But I don't how could I make it. So see anyone can help.
Thank you
Never, ever, ever pass arbitrary binary data to the String
constructor. You don't have encoded text, you have arbitrary bytes. That's not what the String
constructor is for.
Ideally, don't represent the binary data as text at all - but if you have to, do so using base64 or hex, which will encode arbitrary binary data in ASCII.
See more on this question at Stackoverflow