The following should be immensely helpful for people looking to construct JWTs in Apex in a much simpler way than provided in many online examples:
I've been going through the joys of learning to construct a JWT token in Apex, and I found only a couple examples which seemed helpful, though always seemingly overlong and overcomplicated, but in using their methodologies I am still just getting the error "FATAL_ERROR System.SecurityException: Invalid Crypto Key".
I don't have anything to go off of other than that. Anyone spot it below? This is for Snowflake btw.
NOTE: In the example below, I am getting "privateKey" from a rsa_key.p8 file. I also have a rsa_key.pub file, but that is not used in the Crypto.sign() method. I have tried using the text string directly in code, and uploading as a static resource. Since it begins with "-----BEGIN ENCRYPTED PRIVATE KEY-----", it appears that must be removed, otherwise the required EncodingUtil.base64Decode fails with it.
String privateKeyPKCS8 = 'MIIJQwIBADhutg4078gf2fg2f23goesonforeverandamen...';
Long iat = DateTime.now().getTime();
Long exp = DateTime.now().addMinutes(60).getTime();
String base64header = EncodingUtil.base64Encode(blob.valueof('{"alg": "RS256","typ":"JWT"}'));
//system.debug('base64header = '+base64header); //returns static value of: eyJhbGciOiAiUlMyNTYiLCJ0eXAiOiJKV1QifQ
String base64payload = EncodingUtil.base64Encode(blob.valueof('{"iss":"NAME-FQA12325.SFDC_INTEGRATION_USER.SHA256:JUNUEuibBIBU787Gug78g7g9g7RqgF/3LhEU=","sub":"NAME-FQA12325.SFDC_INTEGRATION_USER","iat":'+iat+',"exp":'+exp+'}'));
//system.debug('base64payload = '+base64payload);
String base64signature = EncodingUtil.base64Encode(Crypto.sign('RSA-SHA256', Blob.valueof(base64header +'.'+base64payload), EncodingUtil.base64Decode(privateKeyPKCS8)) );
//system.debug('signature = '+base64signature);
String FinalJWT = base64header+'.'+base64payload+'.'+base64signature;
----------EDIT------------: As mentioned below, these two questions below are similar, but do not address how to troubleshoot "FATAL_ERROR System.SecurityException: Invalid Crypto Key", and do not outline how a Named Credential can be used with a rsa_key.p8 and rsa_key.pub file. The trailhead link is good theoretical knowledge but does not provide direction on how to accomplish the above in any code or otherwise
Generate JWT token for external app
Named Credentials - What is the difference between JWT & JWT Token Exchange