温馨提示×

c#怎么实现sha256加密算法

c#
小亿
141
2024-02-22 09:29:29
栏目: 编程语言

在C#中可以使用SHA256Managed类来实现SHA256加密算法。以下是一个简单的示例代码:

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

public class Program
{
    public static string CalculateSHA256(string input)
    {
        using (SHA256 sha256 = SHA256Managed.Create())
        {
            byte[] bytes = Encoding.UTF8.GetBytes(input);
            byte[] hash = sha256.ComputeHash(bytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }

            return sb.ToString();
        }
    }

    public static void Main()
    {
        string input = "Hello, World!";
        string hash = CalculateSHA256(input);

        Console.WriteLine("Input: " + input);
        Console.WriteLine("SHA256 Hash: " + hash);
    }
}

在上面的示例中,CalculateSHA256方法接受一个字符串输入并返回其SHA256散列值。主函数中演示了如何使用该方法来计算SHA256散列并输出结果。您可以将您要加密的字符串替换为input变量中的内容。

0