generate HMAC-SHA1 in C#

后端 未结 2 747
攒了一身酷
攒了一身酷 2021-01-23 02:05

I am trying to make use of a REST API using C#.

The API creator has provided below pseudo code for hmac creation.

var key1 = sha1(body);
var key2 = key1         


        
2条回答
  •  悲&欢浪女
    2021-01-23 02:36

    The issue to make it work in c# is that you need to take the hex format into consideration and then in some cases for it to work the final result should be lower case (example if you're using this for a quickblox api or something)

        private string GetHashedMessage(String _secret)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] keyByte = encoding.GetBytes(_secret);
            String _message= "Your message that needs to be hashed";
            HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
    
            byte[] messageBytes = encoding.GetBytes(_message);
            byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
            return ByteToString(hashmessage).ToLower();
        }
    
        public string ByteToString(byte[] buff)
        {
            string sbinary = "";
    
            for (int i = 0; i < buff.Length; i++)
            {
                sbinary += buff[i].ToString("X2"); // hex format
            }
            return (sbinary);
        }
    

    reference: http://billatnapier.com/security01.aspx

提交回复
热议问题