当前位置: 移动技术网 > IT编程>开发语言>c# > C#实现Java的DigestUtils.sha256Hex

C#实现Java的DigestUtils.sha256Hex

2019年09月19日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网