Error String Exception Blob is not a valid UTF-8 string

246 views Asked by At

I'm trying to generate jwt token using secret key provided the problem is when i convert the generated hmac blob to string() I'm getting error saying "System.stringException Blob is not a valid UTF-8 String"

How to resolve this ?

Map<String, String> header = new Map<String, String>{
    'alg' => 'HS256',
    'typ' => 'JWT'
};

System.debug(header);

Map<String, Object> claim = new Map<String, Object>{
    'sub' => UserInfo.getUserId(),
    'name' => UserInfo.getName(),
    'iat' => Datetime.now().getTime(),
    'exp' => Datetime.now().getTime() + (60 * 1000) // Adding 60 seconds to the current time in milliseconds
};

System.debug(claim);

String headerBase64 = EncodingUtil.base64Encode(Blob.valueOf(JSON.serialize(header)));
String claimBase64 = EncodingUtil.base64Encode(Blob.valueOf(JSON.serialize(claim)));

String salt = headerBase64 + '.' + claimBase64;
System.debug(salt);

Blob secretToken = Crypto.generateMac('HmacSHA256', Blob.valueOf(salt), Blob.valueOf('Secret_key'));

// HMAC as a binary value, not base64-encoded
String signature =secretToken.toString(); //error saying blob is not a valid UTF-8 String

// Combine components to form the JWT token
String jwtToken = salt + '.' + signature;

// Print or use the JWT token as needed
System.debug(jwtToken);
0

There are 0 answers