[SalesForce] How to create RS256 signature using apex

I read the Question from here: How to create HMAC-SHA-256 signature using apex

I need the same thing but I would like to use the RS256 algorithm.

How can I do it?

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,

Typical cryptographic algorithms used [for signatures] are HMAC with SHA-256 (HS256) and RSA signature with SHA-256 (RS256)

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:

String algorithmName = 'HmacSHA256';
Blob hmacData = Crypto.generateMac(algorithmName, Blob.valueOf(saltValue), Blob.valueOf(secretKeyValue));

According to the documentation for Crypto.generateMAC().

The valid values for algorithmName are:

  • hmacMD5
  • hmacSHA1
  • hmacSHA256
  • hmacSHA512

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:

sign(algorithmName, input, privateKey)

Computes a unique digital signature for the input string, using the specified algorithm and the supplied private key.

Further, RSA-SHA256 is a valid value for algorithmName. So I suspect that you need something like:

string input="...";  // what you want to sign
string privateKey="...";  // your private key
blob rs256sig = Crypto.sign(
    'RSA-SHA256', 
    Blob.valueOf(input), 
    Blob.valueOf(privateKey));

Update: Note that Crypto.sign() returns a blob, which is binary data. If you need the signature in a text format, you can encode it as Base64 or Hex using EncodingUtil. I believe that hex encoding is common for signatures, e.g.,

string hexSignature = EncodingUtil.convertToHex(rs256sig);
Related Topic