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?

  • 2
    Have you tried just changing the algorithm name?
    – Adrian Larson
    Mar 27, 2017 at 15:25

1 Answer 1


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(

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);
  • it is working , but how can I receive the signature ? When I print the blob in the console it is writting Blob[128] and when I am doing rs256sig.toString() ,I receive the error System.StringException: BLOB is not a valid UTF-8 string
    – Raphym
    Mar 28, 2017 at 13:51
  • @Raphym see Update appended to answer. Mar 28, 2017 at 14:43

You must log in to answer this question.

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