I’m trying to generate a Hash-based Message Authentication Code (HAMC) using apex.

.net code for the same is given below:

        string key = "e384c7595e2baf115945bd6c2268157e7972fbebb998d36c40d72e9f37f2f000c5868550ec2092caf5369d2f372f0040b788d38a79b311cbdcdeb14cfc195106";
        long counter = 3396975938055884266;
          string returnVal;

        // convert the key from a hex string to a byte array 
        byte[] binaryKey = HexStringToByteArray(key);
        // Convert the counter to byte array based on pc architecture. 
        // It is signed big endian integer according to OTP documentation. 
        byte[] counterBytes;
        if (BitConverter.IsLittleEndian)
            counterBytes = BitConverter.GetBytes(counter).Reverse().ToArray();
            counterBytes = BitConverter.GetBytes(counter);
        //initizlize the HMAC with a key spec created from the key 
        HMACSHA512 hmac = new HMACSHA512(binaryKey);
        // compute the OTP using the bytes of the counter 
        byte[] computedOtp = hmac.ComputeHash(counterBytes);

        returnVal  = ByteArrayToString(computedOtp);

// output
// 96284f9a911cc1e534e7ab4b07b65b035245e09523c1f6162803cf929375c91078fdb0c3f56cc02207be2489121b0a7aa8a3ecb90c29cfb40816c2430465d5a4

Apex code

string key = 'e384c7595e2baf115945bd6c2268157e7972fbebb998d36c40d72e9f37f2f000c5868550ec2092caf5369d2f372f0040b788d38a79b311cbdcdeb14cfc195106';
string  counter = '3396975938055884266';

Blob mac = crypto.generateMac('hmacSHA512',Blob.valueOf(counter), EncodingUtil.base64decode(key));
string otp = EncodingUtil.convertToHex(mac);

System.debug('otp ->' + otp); 
// b5907926b31583ddf2b0de795ed1a65c631b2c89db3d4e7884da337cdae47b79e0332baa25edcc911e291615b0c424544262fa3a0be5a65706b3ed602432810d

crypto.generateMac is not giving me the same output as .net. what am I missing in Apex code?

  • You're not showing ByteArrayToString implementation, that needs to be covered in Apex. You also need to consider the effects of BitConverter.GetBytes. Suggestion - try to reimplement this in Java, then port it to Apex. Conversion from hex string to a byte array (Blob) should be done via EncodingUtil.convertFromHex rather than base64-decode – identigral Oct 21 '19 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.