C#MD5

  /// <summary>
  /// 以MD5的方式加密指定字符串
  /// </summary>
  /// <param name="cleanString"></param>
  /// <returns></returns>
  public static string Encrypt(string cleanString)
  {
         Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString);
         Byte[] hashedBytes = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
   
         return BitConverter.ToString(hashedBytes);
  }

08-24
在 C# 中,计算字符串或文件的 MD5 哈希值是一种常见的数据完整性验证手段。可以通过 `System.Security.Cryptography` 命名空间中的 `MD5` 类来实现这一功能。以下分别介绍字符串和文件的 MD5 哈希值计算方法。 ### 计算字符串的 MD5 哈希值 要计算字符串的 MD5 哈希值,首先需要将字符串转换为字节数组,然后使用 `MD5` 类进行哈希计算,并将结果格式化为十六进制字符串。 ```csharp using System; using System.Security.Cryptography; using System.Text; class Program { static void Main() { string source = "Hello World!"; using (MD5 md5Hash = MD5.Create()) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } Console.WriteLine("字符串的MD5哈希值是: " + sBuilder.ToString()); } } } ``` 此代码示例中创建的哈希字符串与能创建 32 字符的十六进制格式哈希字符串的任何 MD5 哈希函数兼容[^2]。 ### 计算文件的 MD5 哈希值 计算文件的 MD5 哈希值时,需要打开文件流并将其内容传递给 `MD5` 类进行哈希计算。以下是一个完整的示例: ```csharp using System; using System.IO; using System.Security.Cryptography; class Program { static void Main(string[] args) { string filePath = @"C:\path\to\your\file.txt"; using (MD5 md5Hash = MD5.Create()) { using (FileStream stream = File.OpenRead(filePath)) { byte[] hashValue = md5Hash.ComputeHash(stream); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < hashValue.Length; i++) { sBuilder.Append(hashValue[i].ToString("x2")); } Console.WriteLine("文件的MD5哈希值是: " + sBuilder.ToString()); } } } } ``` 通过这种方式可以计算任意文件的 MD5 值,适用于文件完整性校验等场景[^5]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值