C#(.NET) HMAC SHA256實現

HMAC SHA256的實現比較簡單,能夠用多種語言實現,下面我用C#語言實現,一種結果是居於BASE64,另一種是居於64位。html

C# HMAC SHA256 (Base64)

 

using System.Security.Cryptography;

namespace Test
{
  public class MyHmac
  {
    private string CreateToken(string message, string secret)
    {
      secret = secret ?? "";
      var encoding = new System.Text.ASCIIEncoding();
      byte[] keyByte = encoding.GetBytes(secret);
      byte[] messageBytes = encoding.GetBytes(message);
      using (var hmacsha256 = new HMACSHA256(keyByte))
      {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashmessage);
      }
    }
  }
}

C# HMAC SHA256 (64位原始)

public static string Encrypt(string message, string secret)
            {
                secret = secret ?? "";
                var encoding = new System.Text.UTF8Encoding();
                byte[] keyByte = encoding.GetBytes(secret);
                byte[] messageBytes = encoding.GetBytes(message);
                using (var hmacsha256 = new HMACSHA256(keyByte))
                {
                    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < hashmessage.Length; i++)
                    {
                        builder.Append(hashmessage[i].ToString("x2"));
                    }
                    return builder.ToString();
                }
            }

分享一個本人打造的公衆號吸粉、推廣方案。post

IOS客戶端源碼、API源碼呈獻給你們,完整的示例你們能夠到AppStore下載安裝「知音」ui

相關文章
相關標籤/搜索