IllegalBlockSize Exception When Doing RSA on bytes of Strings

旧时模样 提交于 2019-12-03 21:54:32

If you do this

byte[] ciphertext = RSAEncryption.rSAencrypt(plaintext.getBytes(), pubKeytext);
//String ciphertextString = new String(ciphertext);
//System.out.println(ciphertextString);

PrivateKey privkey = keyPair.getPrivateKey();
byte[] decryptedText = RSAEncryption.rSAdecrypt(ciphertext, privkey);

the code runs perfectly fine. You cannot convert a byte array to a String since the bytes are converted to characters and back to bytes (using getBytes()) - depending on your default charset. new String(ciphertext) strips away unprintable characters which changes the ciphertext and hence makes the plaintext unrecoverable. (Thanks to Artjom B. for pointing that out.)

Simply use Base64 or binary to transport your ciphertext, e.g.:

byte[] ciphertext = RSAEncryption.rSAencrypt(plaintext.getBytes(), pubKeytext);
String ciphertextString = Base64.toBase64String(ciphertext);
System.out.println(ciphertextString);

PrivateKey privkey = keyPair.getPrivateKey();
byte[] decryptedText = RSAEncryption.rSAdecrypt(Base64.decode(ciphertextString), privkey);

(I am using the BouncyCastle Base64 encoder here.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!