VB.net 2010 视频教程 VB.net 2010 视频教程 VB.net 2010 视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > C#编程 >
  • C#教程之C#实现Java的DigestUtils.sha256Hex

  • 2019-09-18 20:36 来源:未知

代码地址:DotNetCore_Practice/JavaToC#/DigestUtils at master · PuzzledAlien/DotNetCore_Practice

public class Hex
{
    /// <summary>
    /// 字节数组转换为Hex字符串
    /// </summary>
    /// <param name="data"></param>
    /// <param name="toLowerCase"></param>
    /// <returns></returns>
    public static string ByteArrayToHexString(byte[] data, bool toLowerCase = true)
    {
        var hex = BitConverter.ToString(data).Replace("-", string.Empty);
        return toLowerCase ? hex.ToLower() : hex.ToUpper();
    }
}
public class DigestUtils
{
    /// <summary>
    /// SHA256 转换为 Hex字符串
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string Sha256Hex(string data)
    {
        var bytes = Encoding.UTF8.GetBytes(data);
        using (var sha256 = SHA256.Create())
        {
            var hash = sha256.ComputeHash(bytes);
            return Hex.ByteArrayToHexString(hash);
        }
    }

    /// <summary>
    /// SHA256 转换为 Hex字符串
    /// </summary>
    /// <param name="data"></param>
    /// <param name="encoding"></param>
    /// <returns></returns>
    public static string Sha256Hex(string data, Encoding encoding)
    {
        var bytes = encoding.GetBytes(data);
        using (var sha256 = SHA256.Create())
        {
            var hash = sha256.ComputeHash(bytes);
            return Hex.ByteArrayToHexString();
        }
    }

    /// <summary>
    /// SHA256 转换为 Hex字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string Sha256Hex(byte[] bytes)
    {
        using (var sha256 = SHA256.Create())
        {
            var hash = sha256.ComputeHash(bytes);
            return Hex.ByteArrayToHexString();
        }
    }
}
相关教程