Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c#md5加密

作者:刺眼的男ren   发布日期:2025-09-24   浏览:31

using System;
using System.Text;
using System.Security.Cryptography;

class Program
{
    static void Main()
    {
        string input = "Hello, World!";
        string hash = GetMd5Hash(input);
        Console.WriteLine("MD5: " + hash);
    }

    static string GetMd5Hash(string input)
    {
        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }
    }
}

解释说明:

  1. 引入命名空间:代码中使用了 System, System.TextSystem.Security.Cryptography 命名空间,分别用于基本类型、字符串编码和加密操作。
  2. Main 方法:程序的入口点,定义了一个字符串 input 并调用 GetMd5Hash 方法获取其 MD5 哈希值,然后将结果输出到控制台。
  3. GetMd5Hash 方法
    • 创建一个 MD5 对象实例。
    • 将输入字符串转换为字节数组(使用 ASCII 编码)。
    • 计算哈希值并返回一个字节数组。
    • 使用 StringBuilder 将字节数组转换为十六进制字符串格式。
  4. MD5.Create():创建一个 MD5 哈希算法的新实例。使用 using 语句确保资源被正确释放。
  5. byte[] inputBytes:将输入字符串转换为字节数组,以便进行哈希计算。
  6. byte[] hashBytes:存储计算后的哈希值。
  7. StringBuilder:用于构建最终的十六进制字符串表示形式。

这样就可以将任意字符串转换为 MD5 哈希值并输出。

上一篇:c# byte[]

下一篇:c#字符串分割

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站