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

.NET6中哈希算法的简化用法的实现

程序员文章站 2022-07-11 15:00:52
目录intronew apisample beforenew api samplemorereferencesintro微软在 .net 6 中引入一些更简单的 api 来使用 hmac 哈希算法(m...

intro

微软在 .net 6 中引入一些更简单的 api 来使用 hmac 哈希算法(md5/sha1/sha256/sha384/sha512)

微软的叫法叫做 hmac one-shoot method, hmac 算法在普通的哈希算法基础上增加了一个 key,通过 key 提升了安全性,能够有效避免密码泄露被彩虹表反推出真实密码, jwt(json web token) 除了可以使用 rsa 方式外也支持使用 hmac 。

new api

新增的 api 定义如下:

namespace system.security.cryptography { 
    public partial class hmacmd5 { 
        public static byte[] hashdata(byte[] key, byte[] source); 
        public static byte[] hashdata(readonlyspan<byte> key, readonlyspan<byte> source); 
        public static int hashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination); 
        public static bool tryhashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination, out int byteswritten); 
    } 
 
    public partial class hmacsha1 { 
        public static byte[] hashdata(byte[] key, byte[] source); 
        public static byte[] hashdata(readonlyspan<byte> key, readonlyspan<byte> source); 
        public static int hashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination); 
        public static bool tryhashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination, out int byteswritten); 
    } 
 
    public partial class hmacsha256 { 
        public static byte[] hashdata(byte[] key, byte[] source); 
        public static byte[] hashdata(readonlyspan<byte> key, readonlyspan<byte> source); 
        public static int hashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination); 
        public static bool tryhashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination, out int byteswritten); 
    } 
 
    public partial class hmacsha384 { 
        public static byte[] hashdata(byte[] key, byte[] source); 
        public static byte[] hashdata(readonlyspan<byte> key, readonlyspan<byte> source); 
        public static int hashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination); 
        public static bool tryhashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination, out int byteswritten); 
    } 
 
    public partial class hmacsha512 { 
        public static byte[] hashdata(byte[] key, byte[] source); 
        public static byte[] hashdata(readonlyspan<byte> key, readonlyspan<byte> source); 
        public static int hashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination); 
        public static bool tryhashdata(readonlyspan<byte> key, readonlyspan<byte> source, span<byte> destination, out int byteswritten); 
    } 
} 

sample before

在之前的版本中想要实现计算 hmac 算法会比较复杂,之前实现了一个 hashhelper 来封装了常用的 hash 算法和 hmac 算法,hashhelper 部分代码如下,完整代码可以从 github 获取:https://github.com/weihanli/weihanli.common/blob/dev/src/weihanli.common/helpers/hashhelper.cs

/// <summary> 
/// 获取哈希之后的字符串 
/// </summary> 
/// <param name="type">哈希类型</param> 
/// <param name="source">源</param> 
/// <param name="key">key</param> 
/// <param name="islower">是否是小写</param> 
/// <returns>哈希算法处理之后的字符串</returns> 
public static string gethashedstring(hashtype type, byte[] source, byte[]? key, bool islower = false) 
{ 
    guard.notnull(source, nameof(source)); 
    if (source.length == 0) 
    { 
        return string.empty; 
    } 
    var hashedbytes = gethashedbytes(type, source, key); 
    var sbtext = new stringbuilder(); 
    if (islower) 
    { 
        foreach (var b in hashedbytes) 
        { 
            sbtext.append(b.tostring("x2")); 
        } 
    } 
    else 
    { 
        foreach (var b in hashedbytes) 
        { 
            sbtext.append(b.tostring("x2")); 
        } 
    } 
    return sbtext.tostring(); 
} 
 
/// <summary> 
/// 计算字符串hash值 
/// </summary> 
/// <param name="type">hash类型</param> 
/// <param name="str">要hash的字符串</param> 
/// <returns>hash过的字节数组</returns> 
public static byte[] gethashedbytes(hashtype type, string str) => gethashedbytes(type, str, encoding.utf8); 
 
/// <summary> 
/// 计算字符串hash值 
/// </summary> 
/// <param name="type">hash类型</param> 
/// <param name="str">要hash的字符串</param> 
/// <param name="encoding">编码类型</param> 
/// <returns>hash过的字节数组</returns> 
public static byte[] gethashedbytes(hashtype type, string str, encoding encoding) 
{ 
    guard.notnull(str, nameof(str)); 
    if (str == string.empty) 
    { 
        return array.empty<byte>(); 
    } 
    var bytes = encoding.getbytes(str); 
    return gethashedbytes(type, bytes); 
} 
 
/// <summary> 
/// 获取hash后的字节数组 
/// </summary> 
/// <param name="type">哈希类型</param> 
/// <param name="bytes">原字节数组</param> 
/// <returns></returns> 
public static byte[] gethashedbytes(hashtype type, byte[] bytes) => gethashedbytes(type, bytes, null); 
 
/// <summary> 
/// 获取hash后的字节数组 
/// </summary> 
/// <param name="type">哈希类型</param> 
/// <param name="key">key</param> 
/// <param name="bytes">原字节数组</param> 
/// <returns></returns> 
public static byte[] gethashedbytes(hashtype type, byte[] bytes, byte[]? key) 
{ 
    guard.notnull(bytes, nameof(bytes)); 
    if (bytes.length == 0) 
    { 
        return bytes; 
    } 
 
    hashalgorithm algorithm = null!; 
    try 
    { 
        if (key == null) 
        { 
            algorithm = type switch 
            { 
                    hashtype.sha1 => new sha1managed(), 
                    hashtype.sha256 => new sha256managed(), 
                    hashtype.sha384 => new sha384managed(), 
                    hashtype.sha512 => new sha512managed(), 
                    _ => md5.create() 
            }; 
        } 
        else 
        { 
            algorithm = type switch 
            { 
                    hashtype.sha1 => new hmacsha1(key), 
                    hashtype.sha256 => new hmacsha256(key), 
                    hashtype.sha384 => new hmacsha384(key), 
                    hashtype.sha512 => new hmacsha512(key), 
                    _ => new hmacmd5(key) 
            }; 
        } 
        return algorithm.computehash(bytes); 
    } 
    finally 
    { 
        algorithm.dispose(); 
    } 
} 

使用示例如下:

hashhelper.gethashedbytes(hashtype.md5, "test"); 
hashhelper.gethashedbytes(hashtype.md5, "test".getbytes()); 
hashhelper.gethashedbytes(hashtype.md5, "test", "testkey"); 
hashhelper.gethashedbytes(hashtype.md5, "test".getbytes(), "testkey".getbytes()); 
 
hashhelper.gethashedstring(hashtype.md5, "test"); 
hashhelper.gethashedstring(hashtype.sha1, "test".getbytes()); 
hashhelper.gethashedstring(hashtype.sha256, "test", "testkey"); 
hashhelper.gethashedstring(hashtype.md5, "test".getbytes(), "testkey".getbytes()); 

new api sample

有了新的 api 以后可以怎么简化呢,来看下面的示例:

var bytes = "test".getbytes(); 
var keybytes = "test-key".getbytes(); 
 
// hmacmd5 
var hmd5v1 = hmacmd5.hashdata(keybytes, bytes); 
var hmd5v2 = hashhelper.gethashedbytes(hashtype.md5, bytes, keybytes); 
console.writeline(hmd5v2.sequenceequal(hmd5v1)); 
 
// hmacsha1 
var hsha1v1 = hmacsha1.hashdata(keybytes, bytes); 
var hsha1v2 = hashhelper.gethashedbytes(hashtype.sha1, bytes, keybytes); 
console.writeline(hsha1v2.sequenceequal(hsha1v1)); 
 
// hmacsha256 
var hsha256v1 = hmacsha256.hashdata(keybytes, bytes); 
var hsha256v2 = hashhelper.gethashedbytes(hashtype.sha256, bytes, keybytes); 
console.writeline(hsha256v2.sequenceequal(hsha256v1)); 
 
// hmacsha384 
var hsha384v1 = hmacsha384.hashdata(keybytes ,bytes); 
var hsha384v2 = hashhelper.gethashedbytes(hashtype.sha384, bytes, keybytes); 
console.writeline(hsha384v2.sequenceequal(hsha384v1)); 
 
// hmacsha512 
var hsha512v1 = hmacsha512.hashdata(keybytes ,bytes); 
var hsha512v2 = hashhelper.gethashedbytes(hashtype.sha512, bytes, keybytes); 
console.writeline(hsha512v2.sequenceequal(hsha512v1)); 

直接使用对应的 hmac 哈希算法的 hashdata 方法即可,传入对应的 key 和 原始内容就可以了,上面是和我们 hashhelper 封装的方法进行对比,看结果是否一致,都是一致的,输出结果如下:

.NET6中哈希算法的简化用法的实现

more

对于普通的哈希算法,微软其实在 .net 5 就已经支持了上面的用法,可以尝试一下下面的代码:

var bytes = "test".getbytes(); 
 
// md5 
var md5v1 = md5.hashdata(bytes); 
var md5v2 = hashhelper.gethashedbytes(hashtype.md5, bytes); 
console.writeline(md5v2.sequenceequal(md5v1)); 
 
// sha1 
var sha1v1 = sha1.hashdata(bytes); 
var sha1v2 = hashhelper.gethashedbytes(hashtype.sha1, bytes); 
console.writeline(sha1v2.sequenceequal(sha1v1)); 
 
// sha256 
var sha256v1 = sha256.hashdata(bytes); 
var sha256v2 = hashhelper.gethashedbytes(hashtype.sha256, bytes); 
console.writeline(sha256v2.sequenceequal(sha256v1)); 
 
// sha384 
var sha384v1 = sha384.hashdata(bytes); 
var sha384v2 = hashhelper.gethashedbytes(hashtype.sha384, bytes); 
console.writeline(sha384v2.sequenceequal(sha384v1)); 
 
// sha512 
var sha512v1 = sha512.hashdata(bytes); 
var sha512v2 = hashhelper.gethashedbytes(hashtype.sha512, bytes); 
console.writeline(sha512v2.sequenceequal(sha512v1)); 

很多时候我们可能都会要使用 md5 或者 sha1 之后的字符串,不知道为什么微软没有直接获取一个字符串的方法,如果有这样一个方法,就会更方便了,相比之后,感觉还是自己封装的 hashhelper 使用起来更舒服一些,哈哈,这样的静态方法不够抽象如果要动态替换哈希算法代码可能就有点...

references

https://github.com/dotnet/runtime/pull/53487
https://github.com/dotnet/runtime/issues/40012
https://github.com/dotnet/core/issues/6569#issuecomment-913876347
https://baike.baidu.com/item/hmac/7307543?fr=aladdin
https://github.com/weihanli/samplesinpractice/blob/master/net6sample/hashsample/program.cs
https://github.com/weihanli/weihanli.common/blob/dev/src/weihanli.common/helpers/hashhelper.cs

到此这篇关于.net 6中哈希算法的简化用法的实现的文章就介绍到这了,更多相关.net 6 哈希算法内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: .NET6 哈希算法