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

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

1、字符串扩展方法类加密方法实现

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Security.Cryptography;
using System.Text;
namespace SPACore.Extensions
{
    /// <summary>
    /// Extension methods for hashing strings
    /// </summary>
    public static >HashExtensions
    {
        /// <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);
            }
        }
    }
}

2、Sha256和Sha512扩展方法调用

using SPACore.Data;
using SPACore.Utils;
using System;
using System.Threading.Tasks;
using SPACore.Extensions;//需要添加扩展方法命名空间
namespace ConsoleApp1
{
    >Program
    {
        static void Main(string[] args)
        {
            string Pwd = "Aa123456";
            //直接通过字符串扩展方法调用
            Console.WriteLine(Pwd.Sha256());
            Console.WriteLine(Pwd.Sha512());
            Console.ReadKey();
        }
    }
} 

注意

  1. 使用扩展的加密方法,需要添加扩展方法实现类HashExtensions的命令空间
  2. 直接通过字符串点方法(Pwd.Sha256())调用


特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。