0

I am trying to encrypt a string using AES256 then converting it to Hex.
I am supplied a Hex key so I tried going online and converting the Hex to text and using that value in my class but I keep getting an error message "Invalid private key. Must be 32 bytes" The think the actual size of the key is 27 bytes and that is the issue. What is a better way to to convert the hex key into a format that I can be used in the encryption? The key I supplied is not the actual result, this is for reference only.

 public static String encrypt(String toEncrypt){

    string nonHexKey = '23432%^$^%^';
    Blob newKey= Blob.valueOf(nonHexKey);


    Blob encrypted = Crypto.encryptWithManagedIV('AES256', newKey,Blob.valueOf(toEncrypt));

    String encodedCiphertextAndIV = EncodingUtil.convertToHex(encrypted);
1
  • 2
    EncodingUtil.convertFromHex is your friend
    – identigral
    Commented May 6, 2022 at 21:41

1 Answer 1

0

Here is an example of encryption and descryption.

String toEncrypt = 'hello';
String hexKey = '353277673346715355447255724d75556b514b38775072456d34335977653377';

Blob newKey = EncodingUtil.convertFromHex(hexKey);
Blob encrypted = Crypto.encryptWithManagedIV('AES256', newKey, Blob.valueOf(toEncrypt));
String encodedCiphertextAndIV = EncodingUtil.convertToHex(encrypted);
System.debug('Encrypted: ' + encodedCiphertextAndIV);

String decrypted = Crypto.decryptWithManagedIV('AES256', newKey, EncodingUtil.convertFromHex(encodedCiphertextAndIV)).toString();
System.debug('Decrypted: ' + decrypted);

Running this code prints

Encrypted: 64e0ac080424eeefde0b550eb93ff239888162fc32b83742967883c24aa5b44a
Decrypted: hello

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .