Reputation: 21
I have an encryption method that works well and passes me an encrypted String.
KeySpec keySpec = new PBEKeySpec(encryptionPassword.toCharArray(), salt, iterations);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
//encryption
Cipher encoder = Cipher.getInstance(key.getAlgorithm());
encoder.init(Cipher.ENCRYPT_MODE, key, paramSpec);
String str_to_encrypt = "Hello";
byte[] enc = encoder.doFinal(str_to_encrypt.getBytes("UTF8"));
System.out.println("encrypted = " + DatatypeConverter.printBase64Binary(enc));
output: encrypted = vjXsSX0cBNc=
However I also wish to Decrypt this String I've recieved, I am having trouble with this however, especially the reverse of getBytes and printBase64Binary.
This is the first time I have attempted to decrypt, so I used a lot of Googling, I found that 'parseBase64Binary' could get bytes from a string, with 'new String(dec, "US-ASCII") then turning the bytes into a string...somewhere something went askew.
//decryption
Cipher encoder = Cipher.getInstance(key.getAlgorithm());
encoder.init(Cipher.DECRYPT_MODE, key, paramSpec);
String str_to_decrypt = "vjXsSX0cBNc=";
byte[] dec = DatatypeConverter.parseBase64Binary(str_to_decrypt);
System.out.println("decrypted = " + new String(dec, "UTF8"));
output: decrypted = ?5?I}?
The only thing I can think of is that I haven't actually decrypted the string properly, as I have not used encoder.doFinal anywhere... somewhat stumped as to where to use it.
Upvotes: 1
Views: 3461
Reputation: 21
EDIT: Answered own question for completeness, all sorted!
Played around a bit more, I was right in saying I hadn't properly decrypted the String as I hadn't used encoder.doFinal... trial and error led me to this:
String str_to_decrypt = "vjXsSX0cBNc=";
byte[] dec = encoder.doFinal(DatatypeConverter.parseBase64Binary(str_to_decrypt));
System.out.println("decrypted = " + new String(dec, "UTF8"));
output: decrypted = Hello
Upvotes: 1