NET Core 通过扩展方法实现密码字符串加密(Sha256和Sha512)

using System;
using System.Security.Cryptography;
using System.Text;
namespace SPACore.Extensions
{
    /// <summary>
    /// Extension methods for hashing strings
    /// </summary>
    public static class HashExtensions
    {
      static void Main(string[] args)
      {
        var secretString = Guid.NewGuid().ToString("N");
         Console.WriteLine($"Guid:{secretString}");
        var wetet = Sha256(secretString);
        Console.WriteLine($"Sha256:{wetet}");
        var sha512 = Sha512(secretString);
         Console.WriteLine($"Sha512:{wetet}");
        Console.ReadKey();
      }
        /// <summary>
        /// Creates a SHA256 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>A hash</returns>
        public static string Sha256(this string input)
        {
            if (String.IsNullOrEmpty(input)) return string.Empty;
            using (var sha = SHA256.Create())
            {
                var bytes = Encoding.UTF8.GetBytes(input);
                var hash = sha.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }
        /// <summary>
        /// Creates a SHA256 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>A hash.</returns>
        public static byte[] Sha256(this byte[] input)
        {
            if (input == null)
            {
                return null;
            }
            using (var sha = SHA256.Create())
            {
                return sha.ComputeHash(input);
            }
        }
        /// <summary>
        /// Creates a SHA512 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>A hash</returns>
        public static string Sha512(this string input)
        {
            if (string.IsNullOrEmpty(input)) return string.Empty;
            using (var sha = SHA512.Create())
            {
                var bytes = Encoding.UTF8.GetBytes(input);
                var hash = sha.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }
    }
}


posted @ 2022-03-09 09:00  悟自省  阅读(338)  评论(0编辑  收藏  举报