问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/43325310/rsa-encyrption-converting-between-bytes-array-and-string