如何将CryptoJS的SHA256转Base64代码转换为C#实现
C# 对应实现方案
结果不一致的核心原因
- 多数错误实现会先将SHA256哈希字节转为十六进制字符串,再对十六进制字符串做Base64编码,和CryptoJS的原始逻辑不符
- 字符串编码不匹配:CryptoJS.SHA256默认按UTF-8编码处理输入字符串,部分实现误用了ASCII、GBK等其他编码
正确实现代码
.NET 5+ 版本(简化API)
using System; using System.Security.Cryptography; using System.Text; public static string GetSha256Base64(string myString) { byte[] inputBytes = Encoding.UTF8.GetBytes(myString); byte[] hashBytes = SHA256.HashData(inputBytes); return Convert.ToBase64String(hashBytes); }
.NET Framework / 低版本.NET 兼容实现
using System; using System.Security.Cryptography; using System.Text; public static string GetSha256Base64(string myString) { byte[] inputBytes = Encoding.UTF8.GetBytes(myString); using (SHA256 sha256 = SHA256.Create()) { byte[] hashBytes = sha256.ComputeHash(inputBytes); return Convert.ToBase64String(hashBytes); } }
验证示例
输入字符串为test时,CryptoJS与上述C#代码的输出均为n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=,结果完全一致。
内容的提问来源于stack exchange,提问作者DavidJ。
相关产品推荐
相关产品推荐

