function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Francesco SciutoFrancesco Sciuto 

Exception thrown when trying to sign with RSA-SHA1 using Crypto.Sign

I am struggling with signing an input with a key generated by using OpenSSL. My code is as follows:

string algorithmName = 'RSA-SHA1' //also tried with 'RSA'

String base64String = 'KBfW9103GQKknExCqOStSmczmNwDNF81yrF04AVvoVI=';
Blob privateKey = EncodingUtil.base64Decode(base64String);
Blob input = Blob.valueOf('12345qwerty');
            
Crypto.sign(algorithmName, input, privateKey);


The base64String is obtained with the command: openssl rand -base64 32

Everytime I run the code I get the following exception in the log:

"common.apex.runtime.impl.ExecutionException: Invalid Crypto Key"|0x4809a271

Does anybody have an idea what am I doing wrong? Thanks

 
Best Answer chosen by Francesco Sciuto
Francesco SciutoFrancesco Sciuto
Thanks Hans for your reply. I found the solution, I was using the wrong function since I need to generate a SHA1 MAC. The correct snippet is:

String algorithmName = 'hmacSHA1';

String base64String = 'KBfW9103GQKknExCqOStSmczmNwDNF81yrF04AVvoVI=';
Blob privateKey = EncodingUtil.base64Decode(base64String);
Blob input = Blob.valueOf('12345qwerty');
            
Crypto.generateMac(algorithmName, input, privateKey);

All Answers

Hans LissHans Liss
For signing with RSA, you need a PKCS8 format RSA private key, which is a bit more than just a 32-byte random text. Refer to this page (https://developer.salesforce.com/page/Apex_Crypto_Class) for more info and some examples on how to generate key pairs. Search for "Digital signatures" on the page.
Francesco SciutoFrancesco Sciuto
Thanks Hans for your reply. I found the solution, I was using the wrong function since I need to generate a SHA1 MAC. The correct snippet is:

String algorithmName = 'hmacSHA1';

String base64String = 'KBfW9103GQKknExCqOStSmczmNwDNF81yrF04AVvoVI=';
Blob privateKey = EncodingUtil.base64Decode(base64String);
Blob input = Blob.valueOf('12345qwerty');
            
Crypto.generateMac(algorithmName, input, privateKey);
This was selected as the best answer
孝純 黄孝純 黄
The key points are:
1. Remove `-----START PRIVATE KEY-----` 
2. Remove `-----END PRIVATE KEY-----`,
3. Remove all line changes `\n`