I am trying to implement RSA encryption which is able to do the following:
- accept a string value as an input to encrypt using a public key
- return the encrypted cipher as string
- accept the encrypted cipher as an input to decrypt using a private key
- return the original value, decrypted
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 byte
s 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?