You must follow the Following link it will be helpful for you to understand the Signature varification in Salesforce Apex.
For SHA1
you can use the below code snippet:
private String getMac(String RequestString, String secretkey) {
String algorithmName = ‘hmacSHA1′; // the other options are: hmacMD5, hmacSHA256, and hmacSHA512
Blob input = Blob.valueOf(RequestString);
Blob signing =Crypto.generateMac(algorithmName, input, secretkey);
String str=EncodingUtil.urlEncode(EncodingUtil.base64Encode(signing), ‘UTF-8′);
use this str if you want signature in url encode if you want it in base64encode
form only, then use the below code in place of str:
String str=EncodingUtil.base64Encode(signing);
For HMACSHA256
you can use the below code snippet:
string timestamp1 = datetime.now().formatGmt('EEE, d MMM yyyy HH:mm:ss Z');
String action = 'Action';
String algorithmName = 'HMACSHA256';
Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(timestamp1),
Blob.valueOf(Secretkey));
String macUrl =EncodingUtil.base64Encode(mac);
Use the str/macUrl where you want to use Signature may be it in the header if you use the POST
method.
For Sha-1 signature in APEX You can follow the below three links:
http://www.tgerm.com/2012/07/sha-1-apex-rackspace-salesforce.html AND
http://blog.jeffdouglas.com/2010/07/06/using-rsa-sha1-with-salesforce-crypto-class/
and
http://wiki.developerforce.com/page/Apex_Crypto_Class
You are encoding it wrong. Try below code:
Blob blobSignature = Crypto.generateMac('hmacSHA256', Blob.valueOf('testmessage'), Blob.valueOf('123456789'));
System.debug(EncodingUtil.convertToHex(blobSignature));
output
17:42:10:023 USER_DEBUG [56]|DEBUG|9cba4d1d75689509208a97b1ca42f786a630a891e2410bfb11a84feb7a4807ad
Best Answer
DISCLAIMER: I'm not a crypto expert, this is an informed guess using the linked references.
According to the Wikipedia article on JSON Web Tokens,
Sp "HS256" refers to an HMAC, which Wikipedia defines as a "Hash-based message authentication code", where as "RS256" is an "RSA Signature" (not an HMAC), but both are computed using the same hash type (SHA-256).
The answer you link to generated the signature using
Crypto.generateMAC()
as follows:According to the documentation for Crypto.generateMAC().
So no "RS256" in the list, but the method is named
CreateMAC()
, and from the above we believe the RS256 is a signature, not an HMAC. Looking at the Crypto library we see:Further,
RSA-SHA256
is a valid value foralgorithmName
. So I suspect that you need something like:Update: Note that
Crypto.sign()
returns ablob
, which is binary data. If you need the signature in a text format, you can encode it as Base64 or Hex usingEncodingUtil
. I believe that hex encoding is common for signatures, e.g.,