function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Frank van Meegen 42Frank van Meegen 42 

HmacSHA512 from JavaScript example to APEX

Hi all,

I'm trying to reproduce a javascript example for encryption in APEX. The javascript example looks like:
 
function makeSignature(nonce, data, command_url)
{
	const hashstring = nonce + data;
	const hashed = CryptoJS.SHA256(hashstring).toString(CryptoJS.enc.Latin1);
 	const encoded = CryptoJS.enc.Latin1.parse(command_url.concat(hashed));

 	return CryptoJS.HmacSHA512(encoded, API_SECRET).toString(CryptoJS.enc.Base64);
}
nonce = must always be an incremental value to prevent duplicates. Please use an unsigned 64 bit integer. To generate nonce values it is recommended to use time-related functions or other sequences.
data = 'username=' + convertUsername(API_USER) + '&nonce='+nonce;
command_url = '/v1/transaction/getBalance';

The code I have reproduced based on the example is as follows. Unfortunately this gives me an error "SIGNATURE_CHECK_FAILED" so I must be taking a wrong step.
public static String makeSignature(String nonce, String data, String command_url, String SecretKey){
        
        String hashstring = nonce + data;        
        
        String algorithmName256 = 'HmacSHA256';
        Blob HmacSHA256 = Crypto.generateMac(algorithmName256, Blob.valueOf(hashstring),Blob.valueOf(command_url));
        system.debug('HmacSHA256: ' + HmacSHA256);
        
        String algorithmName512 = 'HmacSHA512';
        Blob HmacSHA512 = Crypto.generateMac(algorithmName512, HmacSHA256,Blob.valueOf(SecretKey));
        
        system.debug('HmacSHA512: ' + HmacSHA512);
        
        return EncodingUtil.convertToHex(HmacSHA512);
Can someone please help me with the right steps?