Reputation: 561
I am a new bee to Java Security and Crypto. Below code does not return me the correct decryption.
Also please let me know any recommendation for using an algorithm to make a strong key.
Below code has two methods one is for encryption a String and the other is for decryption.
public class TestSecurityDiscussions {
public static byte[] encryptData(KeyPair keys){
String rawData = "Hi how are you>?";
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.ENCRYPT_MODE, keys.getPublic());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encrypted = cipher.doFinal(rawData.getBytes());
return encrypted;
}
public static String decryptData(byte[] encrypted,KeyPair keys) {
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
} catch (Exception e) {
e.printStackTrace();
}
byte[] deycrypted = cipher.doFinal(encrypted);
return deycrypted.toString();
}
public static void main(String[] args) {
KeyPair keys = KeyPairGenerator.getInstance("RSA").generateKeyPair();
byte[] keydata = encryptData(keys);
System.out.println("======>"+decryptData(keydata,keys));
}
}
Upvotes: 1
Views: 264
Reputation: 39698
I think your problem is this line:
return decrypted.toString();
Byte Strings will give a memory location via the toString()
. You should do this:
return new String(decrypted);
Upvotes: 1