You need to sign in to do that
Don't have an account?
How To Store And Use Without Error A Valid SecretKey Generated By Crypto.generateAesKey(128)
Hello,
I require to create a private aes128 key, store the key in my org and use this key for encrypting and decrypting values. I've run into the following challenges though and have been a bit stumped by them.
- If I create a secret key using
Blob cryptoKey = Crypto.generateAesKey(128);
If I use the following to get the key I get an "BLOB is not a valid UTF-8 string" error.
String cryptoString = cryptoKey.toString();
System.debug('cryptoString= ' + cryptoString);
If I instead convert my created key to a hex value and use it in a encryptWithManagedIV( function I get the following error
"Invalid private key. Must be 16 bytes."
String hexRep = EncodingUtil.convertToHex(cryptoKey);
System.debug('hexRep=' + hexRep);
Crypto.encryptWithManagedIV('AES128', Blob.valueOf(hexRep), Blob.valueOf('just4testing'));
However using the generated crypto key directly in encryptwithManagedIV works fine
Blob encryptedData = Crypto.encryptWithManagedIV('AES128', Crypto.generateAesKey(128), Blob.valueOf('just4testing'));
As I wish to store my secret key generated by Crypto.generateAesKey(128) , as the hex represenation of it won';t work I guess I would need to store the BLOB in a field in my org. This seems a bit unusual to me however can it even be done?
Can a BLOB be stored in a custom field? If not does anyone know why I get an error with my HEX represenation of the secretkey above?
Thanks in advance for any help on this.
Don't use the BLOB's toString method, rather encode it using the Base64 encoder of Salesforce to turn the BLOB into a string you can store. From there you can read the base64 string from Salesforce, decode it back into a BLOB and use it as your key to use. The same principle can be applied to the values you're encrypting (if you need to store them in Salesforce).
Try this quick code sample I've written to test this (can be run in anonymous Apex)
All Answers
Don't use the BLOB's toString method, rather encode it using the Base64 encoder of Salesforce to turn the BLOB into a string you can store. From there you can read the base64 string from Salesforce, decode it back into a BLOB and use it as your key to use. The same principle can be applied to the values you're encrypting (if you need to store them in Salesforce).
Try this quick code sample I've written to test this (can be run in anonymous Apex)
Anyone help me how can I create a website like tesler software (https://tesler-trading.net/tesler-software-review/) this.
Thanks