I am trying to implement RSA encryption which is able to do the following:
I am able to get the encryption/decryption working if I directly decrypt the byte array returned by the encryption, but annot seem to get it to work if I parse the byte array to a String and then back to bytes again.
The following code does work:
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
returnValue += new String(cipherBytes);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(cipherBytes);
System.out.println("plain : " + new String(plainText));
The following code does NOT work:
byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
returnValue += new String(cipherBytes);
String cipherText = new String(cipherBytes);
byte[] reCipherBytes = cipherText.getBytes();
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(reCipherBytes);
System.out.println("plain : " + new String(plainText));
Can anyone advise what I'd need to do to get the second version to work successfully?
I think your problem is because of the default java ecoding/deconding charset when converting a byte array to string and vice-versa.
I have debugged your code and reCipherBytes has not the same length as cipherBytes, that is why the second code blocks throws an exception.
I recomend you to use base64 encoding for transforming cipherBytes into a string.
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
String returnValue = new String(cipherBytes);
String cipherText = Base64.getEncoder().encodeToString(cipherBytes);
byte[] reCipherBytes = Base64.getDecoder().decode(cipherText);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainText = cipher.doFinal(reCipherBytes);
System.out.println("plain : " + new String(plainText));
This code fragment should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With