c#

如何用C#进行哈希加密

小樊
81
2024-09-14 23:47:05
栏目: 编程语言

在C#中,可以使用System.Security.Cryptography命名空间下的类来实现哈希加密

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

class Program
{
    static void Main()
    {
        string input = "Hello, World!"; // 要加密的字符串

        // 使用SHA256哈希算法
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = sha256.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i< hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
            }
            Console.WriteLine("SHA256哈希值: " + sb.ToString());
        }

        // 使用MD5哈希算法
        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i< hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
            }
            Console.WriteLine("MD5哈希值: " + sb.ToString());
        }
    }
}

这个示例首先创建了一个字符串input,然后分别使用SHA256和MD5哈希算法对其进行加密。ComputeHash方法接收一个字节数组作为输入,返回一个包含哈希值的字节数组。最后,将哈希值转换为16进制字符串并输出。

注意:哈希加密是不可逆的,因此无法从哈希值还原原始数据。它通常用于验证数据的完整性和安全存储密码等敏感信息。

0
看了该问题的人还看了