首页 > 代码库 > DotNet中几种常用的加密算法
DotNet中几种常用的加密算法
在.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); } }
以上是一些较为常用的算法代码。
本文出自 “彭泽0902” 博客,请务必保留此出处http://pengze0902.blog.51cto.com/7693836/1864304
DotNet中几种常用的加密算法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。