1

This is my C# code.

private static string CEncrypt()
    {
        const string key = "SECRET KEY";
        const string message = "SECRET MESSAGE";
        var encoding = new UTF8Encoding();
        byte[] keyByte = encoding.GetBytes(key);
        var hmacsha1 = new HMACSHA1(keyByte);
        byte[] messageBytes = encoding.GetBytes(message);
        byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
        return BitConverter.ToString(hashmessage).Replace("-","").ToLower();
    }

This is my Apex Code.

@RestResource(urlMapping='/Encrypt/*')
global with sharing class EncryptTest
{

    @HttpGet
    global static String GetTest()
    {
     string privateKey = 'SECRET KEY';
     Blob cryptoKey  = EncodingUtil.base64Decode(privateKey);
     String message =  'SECRET MESSAGE';                                  
     Blob urlBlob = EncodingUtil.base64Decode(message);
     Blob encryptedData = Crypto.generateMac('hmacSHA1', urlBlob, cryptoKey);
     return EncodingUtil.convertToHex(encryptedData);
    }
}

When I compare the output of the two methods, I am expecting to see the exact same hash. The values from the two methods are: **

Salesforce Hash: "92599d3f792af33a7335c802bb42593f1c59dc2d"
CSharp  Hash 08e21bc5d10b096727c5b91ce32c5384082126c8

**

1 Answer 1

1

They are different because your Apex code is not creating the same byte array that is created in C#. In apex your are calling

  string privateKey = 'SECRET KEY';
  Blob cryptoKey = EncodingUtil.base64Decode(privateKey);

but privateKey is not base64 encoded. base64Encode and base64Decode is not needed here. You need to convert your privateKey to a byte array. Try this

  @RestResource(urlMapping='/Encrypt/*')
  global with sharing class EncryptTest
  {
     @HttpGet
     global static String GetTest()
     {
        string privateKey = 'SECRET KEY';
        Blob cryptoKey  = Blob.valueOf(privateKey);
        String message =  'SECRET MESSAGE';                                  
        Blob urlBlob = Blob.valueOf(message);
        Blob encryptedData = Crypto.generateMac('hmacSHA1', urlBlob, cryptoKey);
        return EncodingUtil.convertToHex(encryptedData);
     }
  }
0

You must log in to answer this question.

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