zoukankan      html  css  js  c++  java
  • C#(.NET) HMAC SHA256实现

    HMAC SHA256的实现比较简单,可以用多种语言实现,下面我用C#语言实现,一种结果是居于BASE64,另外一种是居于64位。

    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();
                    }
                }

    分享一个本人打造的公众号吸粉、推广方案。

    IOS客户端源码、API源码呈献给大家,完整的示例大家可以到AppStore下载安装“知音”

  • 相关阅读:
    逗号操作符使用小技巧
    字符解码?
    画图 wx.Window pen
    进程和线程
    内存管理
    简单的文本编辑器
    迭代器 Iterator
    文件操作
    ebay api学习
    一,wxpython入门
  • 原文地址:https://www.cnblogs.com/jonlan/p/10112455.html
Copyright © 2011-2022 走看看