I am tring to do a simply encryption and decryption. The encrypted blob is encoded to a base64 string so that it can be used as a parameter on a URL. It seems however that changing the encrypted blob to a string and then back to a blob from the URL is screwing with the data and decrypts to a differenct value.
This snippet simulates the conversion to a string for URL and back again to a blob for decryption. I encrypt '123' and i get back '120='. I cant figure out why.
Blob cryptoKey = Crypto.generateAesKey(256);
String UUID = '123';
Blob data = EncodingUtil.base64Decode(UUID);
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
String token = EncodingUtil.base64Encode(encryptedData);
Blob formattedToken = EncodingUtil.base64Decode(token);
Blob decryptedData = Crypto.decryptWithManagedIV('AES256', cryptoKey, encryptedData);
System.debug(EncodingUtil.base64Encode(decryptedData));
I also tried using the below but it too it also returns the same. Encrypting and/or decrypting ciphertext with the provided Initialization Vector (IV)
Blob cryptoKey = Crypto.generateAesKey(256);
String UUID = '123';
Blob data = EncodingUtil.base64Decode(UUID);
Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
String hexedEncryptedDataAndIV = EncodingUtil.convertToHex(encryptedData);
String hexedEncryptedData = hexedEncryptedDataAndIV.substring(32);
String hexedIV = hexedEncryptedDataAndIV.substring(0,32);
Blob ciphertext = EncodingUtil.convertFromHex(hexedEncryptedData);
Blob IV = EncodingUtil.convertFromHex(hexedIV);
Blob decryptedData = Crypto.decrypt('AES256', cryptoKey, IV, ciphertext);
System.debug(EncodingUtil.base64Encode(decryptedData));//"120="
Anyone have any suggestions about what is wrong and how to fix it? Thanks