欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现Java的DigestUtils.sha256Hex

程序员文章站 2022-08-05 23:10:07
代码地址: "DotNetCore_Practice/JavaToC /DigestUtils at master · PuzzledAlien/DotNetCore_Practice" ......

代码地址: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();
        }
    }
}