在.NET項目中,我們較多的使用到加密這個操作。因為在現代的項目中,對信息安全的要求越來越高,那麼多信息的加密就變得至關重要。現在提供幾種常用的加密/解密算法。
1.用於文本和Base64編碼文本的互相轉換 和 Byte[]和Base64編碼文本的互相轉換:
(1).將普通文本轉換成Base64編碼的文本
/// <summary> /// 將普通文本轉換成Base64編碼的文本 /// </summary> /// <param name="value">普通文本</param> /// <returns></returns> public static string StringToBase64String(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(value); } try { var binBuffer = (new UnicodeEncoding()).GetBytes(value); var base64ArraySize = (int)Math.Ceiling(binBuffer.Length / 3d) * 4; var charBuffer = new char[base64ArraySize]; Convert.ToBase64CharArray(binBuffer, 0, binBuffer.Length, charBuffer, 0); var s = new string(charBuffer); return s; } catch (Exception ex) { throw new Exception(ex.Message); } }
(2).將Base64編碼的文本轉換成普通文本
/// <summary> /// 將Base64編碼的文本轉換成普通文本 /// </summary> /// <param name="base64">Base64編碼的文本</param> /// <returns></returns> public static string Base64StringToString(string base64) { if (string.IsNullOrEmpty(base64)) { throw new ArgumentNullException(base64); } try { var charBuffer = base64.ToCharArray(); var bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length); return (new UnicodeEncoding()).GetString(bytes); } catch (Exception ex) { throw new Exception(ex.Message); } }
(3).將Byte[]轉換成Base64編碼文本
/// <summary> /// 將Byte[]轉換成Base64編碼文本 /// </summary> /// <param name="binBuffer">Byte[]</param> /// <returns></returns> public string ToBase64(byte[] binBuffer) { if (binBuffer == null) { throw new ArgumentNullException("binBuffer"); } try { var base64ArraySize = (int)Math.Ceiling(binBuffer.Length / 3d) * 4; var charBuffer = new char[base64ArraySize]; Convert.ToBase64CharArray(binBuffer, 0, binBuffer.Length, charBuffer, 0); var s = new string(charBuffer); return s; } catch (Exception ex) { throw new Exception(ex.Message); } }
(4).將Base64編碼文本轉換成Byte[]
/// <summary> /// 將Base64編碼文本轉換成Byte[] /// </summary> /// <param name="base64">Base64編碼文本</param> /// <returns></returns> public byte[] Base64ToBytes(string base64) { if (string.IsNullOrEmpty(base64)) { throw new ArgumentNullException(base64); } try { var charBuffer = base64.ToCharArray(); var bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length); return bytes; } catch (Exception ex) { throw new Exception(ex.Message); } }
2. DES加密/解密類。
(1).加密
private static readonly string KEY = "pengze0902"; /// <summary> /// 加密 /// </summary> /// <param name="Text"></param> /// <returns></returns> public static string Encrypt(string Text) { return Encrypt(Text, KEY); } /// <summary> /// 加密數據 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Encrypt(string Text, string sKey) { var des = new DESCryptoServiceProvider(); var inputByteArray = Encoding.Default.GetBytes(Text); var bKey = Encoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); des.Key = bKey; des.IV = bKey; var ms = new System.IO.MemoryStream(); var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); var ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } return ret.ToString(); }
(2).解密
private static readonly string KEY = "pengze0902"; /// <summary> /// 解密 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string Decrypt(string text) { return Decrypt(text, KEY); } /// <summary> /// 解密數據 /// </summary> /// <param name="text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Decrypt(string text, string sKey) { var des = new DESCryptoServiceProvider(); var len = text.Length / 2; byte[] inputByteArray = new byte[len]; int x; for (x = 0; x < len; x++) { var i = Convert.ToInt32(text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } var bKey = Encoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); des.Key = bKey; des.IV = bKey; System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); }
(3).取得MD5加密串
//// <summary> /// 取得MD5加密串 /// </summary> /// <param name="input">源明文字符串</param> /// <returns>密文字符串</returns> public static string Md5Hash(string input) { var md5 = new MD5CryptoServiceProvider(); var bs = Encoding.UTF8.GetBytes(input); bs = md5.ComputeHash(bs); var s = new StringBuilder(); foreach (var b in bs) { s.Append(b.ToString("x2").ToUpper()); } var password = s.ToString(); return password; }
3.MD5加密
(1). 32位大寫
/// <summary> /// 32位大寫 /// </summary> /// <returns></returns> public static string Upper32(string s) { var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5"); if (hashPasswordForStoringInConfigFile != null) s = hashPasswordForStoringInConfigFile.ToString(); return s.ToUpper(); }
(2). 32位小寫
/// <summary> /// 32位小寫 /// </summary> /// <returns></returns> public static string Lower32(string s) { var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5"); if (hashPasswordForStoringInConfigFile != null) s = hashPasswordForStoringInConfigFile.ToString(); return s.ToLower(); }
(3).16位大寫
/// <summary> /// 16位大寫 /// </summary> /// <returns></returns> public static string Upper16(string s) { var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5"); if (hashPasswordForStoringInConfigFile != null) s = hashPasswordForStoringInConfigFile.ToString(); return s.ToUpper().Substring(8, 16); }
(4).16位小寫
/// <summary> /// 16位小寫 /// </summary> /// <returns></returns> public static string Lower16(string s) { var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5"); if (hashPasswordForStoringInConfigFile != null) s = hashPasswordForStoringInConfigFile.ToString(); return s.ToLower().Substring(8, 16); }
4.Sha1簽名算法
/// <summary> /// 簽名算法 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetSha1(string str) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(str); } try { //建立SHA1對象 SHA1 sha = new SHA1CryptoServiceProvider(); //將mystr轉換成byte[] var enc = new ASCIIEncoding(); var dataToHash = enc.GetBytes(str); //Hash運算 var dataHashed = sha.ComputeHash(dataToHash); //將運算結果轉換成string var hash = BitConverter.ToString(dataHashed).Replace("-", ""); return hash; } catch (Exception ex) { throw new Exception(ex.Message); } }
5.Sha256加密算法
/// <summary> /// 將字符串轉換為sha256散列 /// </summary> /// <param name="data">字符串進行轉換</param> /// <returns>sha256散列或null</returns> public static string ToSha256(this string data) { try { if (string.IsNullOrEmpty(data)) return null; var hashValue = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(data)); var hex = hashValue.Aggregate("", (current, x) => current + String.Format("{0:x2}", x)); if (string.IsNullOrEmpty(hex)) throw new Exception("Erro creating SHA256 hash"); return hex; } catch (Exception e) { throw new Exception(e.Message, e); } }
以上是一些較為常用的算法代碼。