SHA-256算法原理
SHA-256算法是一种安全散列算法,由美国国家安全局(NSA)提出,是SHA-2家族的一个成员,是美国政府的安全标准,用于确保信息传输安全。SHA-256算法的输入是任意长度的数据,输出是一个256位的散列值。SHA-256算法的特点是输出的长度是固定的,且算法具有不可逆的特性,即不可从散列值反推原文。
C#实现方法
C#实现SHA-256算法的方法如下:
//使用System.Security.Cryptography命名空间
using System.Security.Cryptography;
//获取SHA-256算法
SHA256 sha256 = SHA256.Create();
//输入原文
string source = "Hello World";
//将原文转换成字节数组
byte[] sourceBytes = Encoding.Default.GetBytes(source);
//计算散列值
byte[] hashBytes = sha256.ComputeHash(sourceBytes);
//将散列值转换成字符串
string hash = BitConverter.ToString(hashBytes).Replace("-", "");
//输出结果
Console.WriteLine(hash);
JS实现方法
JS实现SHA-256算法的方法如下:
//输入原文
var source = "Hello World";
//将原文转换成字节数组
var sourceBytes = new TextEncoder("utf-8").encode(source);
//计算散列值
var hashBytes = await crypto.subtle.digest("SHA-256", sourceBytes);
//将散列值转换成字符串
var hash = Array.from(new Uint8Array(hashBytes)).map(b => b.toString(16).padStart(2, '0')).join('');
//输出结果
console.log(hash);