whitefox 發表於 2023-5-29 09:26:50

[C#] MD5/SHA/SHA256/SHA384/SHA512等加密方法

本帖最後由 whitefox 於 2023-5-29 13:29 編輯

這裡透過System.Security.Cryptography.HashAlgorithm來實現各種Hash加密演算法
這篇只有加密沒有解密!
PS: 輸出文字前只要加 $ 就可以了using System;
using System.Security.Cryptography;
using System.Text;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "~沒加密的明文~";
            string[] encryptTypes = new[] { "md5", "sha1", "sha256", "sha384", "sha512" };
            foreach (string encryptType in encryptTypes)
            {
                string encryptText = Encrypt(text, encryptType);
                Console.WriteLine($@"【{text}】經【{encryptType}】加密後:{encryptText}");
            }
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="value">加密字串</param>
        /// <param name="encryptType">加密方式</param>
        /// <returns></returns>
        public static string Encrypt(string value, string encryptType)
        {
            if (string.IsNullOrEmpty(value)) return value;

            using (var hashAlgorithm = HashAlgorithm.Create(encryptType))
            {
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(value);
                buffer = hashAlgorithm.ComputeHash(buffer);
                hashAlgorithm.Clear();

                //使用hex格式輸出
                StringBuilder result = new StringBuilder();
                foreach (byte b in buffer)
                {
                    result.AppendFormat("{0:x2}", b);
                }
            }
        }
    }
}
頁: [1]
查看完整版本: [C#] MD5/SHA/SHA256/SHA384/SHA512等加密方法