什么是哈希算法呢?简单地讲,他是一种为任意大小信息创建一种非常小且固定长度的指纹的方法。哈希算法也称作散列函数。
毫不夸张的说,没有哈希算法就没有区块链的成功,它是区块链的基石。
在区块链中信息的指纹高频率的作为信息的指针使用。根据指纹就可以锁定信息,既可以保证信息的不可篡改性,也能用于定位信息,方便读取和校验信息。
NET 6中哈希算法的简化用法
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);
}
}