版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/CJB_King/article/details/52979633
最近帮老师整理一个ASP.Net项目,其中的用户登录注册需要对用户的密码进行数据加密,我用的是MD5加密,首先在用户注册时把其密码加密保存到数据库,验证登录密码时只需要再次将用户输入的密码加密与其注册时保存到数据库的密码对比,如果一样,则登录成功,好了废话不多说,直接看项目代码吧!
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Web; namespace MyMD5 { public class MyMD5 { public static string Encrypt(string str) //32位加密; { MD5 md5 = new MD5CryptoServiceProvider(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str); //采用Utf8将要加密的字符串编码为byte数组; bytes = md5.ComputeHash(bytes); //采用MD5再次编码 md5.Clear(); string ret = ""; for (int i = 0; i < bytes.Length; i++) { ret += Convert.ToString(bytes[i], 16).PadLeft(2,'0');//将每个字符转化为16进制; } return ret.PadLeft(32,'0'); } //16位加密略 } }
使用时可以像这样:string result = MyMD5.MyMD5.Encrypt(pwdTxt.Text);
result即为加密后的值;
public static string GetMD5(string str) { MD5 md5 = MD5.Create(); //创建MD5对象; byte[] buffer = System.Text.Encoding.GetEncoding("GBK").GetBytes(str); byte[] md5Buffer = md5.ComputeHash(buffer); string strNew = ""; for (int i = 0; i < md5Buffer.Length; i++) { strNew += md5Buffer[i].ToString("x2"); } return strNew; }
以上是我对MD5加密的使用,不足之处望指出哦,大家共同进步!!!
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句