这期内容当中小编将会给大家带来有关怎么在.net core中利用MD5对字符串进行加密解密,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
具体内容如下
/// <summary> /// 加密 /// </summary> /// <param name="Text">要加密的文本</param> /// <param name="sKey">秘钥</param> /// <returns></returns> public static string Encrypt(string Text, string sKey="test") { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray; inputByteArray = Encoding.Default.GetBytes(Text); des.Key = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0,8)); des.IV = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } md4j= ret.ToString(); return ret.ToString(); }
/// <summary> /// 解密 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Decrypt(string Text, string sKey = "test") { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); int len; len = Text.Length / 2; byte[] inputByteArray = new byte[len]; int x, i; for (x = 0; x < len; x++) { i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8)); 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()); }
/// <summary> /// 32位MD5加密 /// </summary> /// <param name="input"></param> /// <returns></returns> private static string Md5Hash(string input) { MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); }
调用加密 解密看效果
public static string md4j = ""; static void Main(string[] args) { //加密 Encrypt("123456"); Decrypt(md4j); }
上述就是小编为大家分享的怎么在.net core中利用MD5对字符串进行加密解密了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。