.NET 7中如何替代Security.Cryptography.MD5Cng实现哈希功能?
问题解决:.NET 7中替代MD5Cng的方案
原因说明
MD5Cng是.NET Framework中Windows平台专属的MD5实现类,.NET 7作为跨平台框架,已移除这类平台绑定的加密类,转而采用统一的抽象接口+工厂方法模式,因此直接引用会提示类型未定义。
解决方案分两种场景:
1. 仅在Windows环境运行,保留类实例化方式
若程序仅需在Windows上运行,可通过以下步骤恢复MD5Cng的使用:
- 安装NuGet包:
System.Security.Cryptography.Cng - 在文件顶部导入正确的命名空间:
Imports System.Security.Cryptography - 修改后的代码(推荐添加Using块释放资源,核心逻辑不变):
Public Function compute64bitHash(ByVal someString As String) As Int64 Using md5 = New MD5Cng() Dim hashmd5 = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(someString)) Dim hashmd5long = System.BitConverter.ToInt64(hashmd5, 0) Return hashmd5long End Using End Function
2. 跨平台兼容方案(推荐)
若需要程序在Windows、Linux、macOS等多平台运行,直接使用.NET 7内置的标准MD5实现即可,计算结果和原MD5Cng完全一致(MD5算法是标准的,不同合规实现输出相同哈希值)。
有两种写法:
写法一:使用工厂方法创建MD5实例
Public Function compute64bitHash(ByVal someString As String) As Int64 Using md5 = MD5.Create() Dim hashmd5 = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(someString)) Dim hashmd5long = System.BitConverter.ToInt64(hashmd5, 0) Return hashmd5long End Using End Function
写法二:使用.NET 5+新增的静态HashData方法(更简洁)
Public Function compute64bitHash(ByVal someString As String) As Int64 Dim inputBytes = System.Text.Encoding.UTF8.GetBytes(someString) Dim hashmd5 = MD5.HashData(inputBytes) Dim hashmd5long = System.BitConverter.ToInt64(hashmd5, 0) Return hashmd5long End Function
补充说明
你之前添加的Imports System.Security.Cryptography.MD5是错误的,MD5是类而非命名空间,正确的命名空间是System.Security.Cryptography,导入后才能识别MD5相关类型。
内容的提问来源于stack exchange,提问作者user4951
相关产品推荐
相关产品推荐

