SHA加密有很多種版本,像是SHA1、SHA256….等
下面用一個Function來實作.NET中所有的SHA加密
using System; using System.Security.Cryptography; using System.Text; namespace SystemAPI.Function.EncryptLibrary { public class EncryptSHA { /// <summary> /// 使用SHA加密訊息 /// </summary> /// <param name="sourceMessage">原始資訊</param> /// <param name="SHAType">SHA加密方式</param> /// <returns>string</returns> public string Encrypt(string sourceMessage, EnumSHAType SHAType) { if (string.IsNullOrEmpty(sourceMessage)) { return string.Empty; } //字串先轉成byte[] byte[] Message = Encoding.Unicode.GetBytes(sourceMessage); HashAlgorithm HashImplement = null; //選擇要使用的SHA加密方式 switch (SHAType) { case EnumSHAType.SHA1: HashImplement = new SHA1Managed(); break; case EnumSHAType.SHA256: HashImplement = new SHA256Managed(); break; case EnumSHAType.SHA384: HashImplement = new SHA384Managed(); break; case EnumSHAType.SHA512: HashImplement = new SHA512Managed(); break; } //取Hash值 byte[] HashValue = HashImplement.ComputeHash(Message); //把byte[]轉成string後,再回傳 return BitConverter.ToString(HashValue).Replace("-","").ToLower(); } public enum EnumSHAType { SHA1, SHA256, SHA384, SHA512 } } }
.
使用方式如下:
EncryptSHA SHA = new EncryptSHA(); string EncryptString = SHA.Encrypt("12345", EncryptSHA.EnumSHAType.SHA512);
One thought on “在.NET上實作SHA加密”