引言:
在项目中我们常常会对输入的密码进行加密,用来维护系统的安全。这次采用的方法是用MD5进行加密,该算法有压缩性、容易计算、抗修改性、强抗碰撞等诸多好处,现总结代码如下,以备后需。
方法:
1.写一个专门的工具类用来对某些字符串进行加密,在其它地方调用即可。(代码如下)
2.通常不会用到解密,对新输入的内容进行加密与之前的密文比对即可。
3.需要的话可以对密码进行32位加密。
代码(C#版):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
public class Tool
{
public static string _KEY = "********"; //密钥
public static string _IV = "########"; //向量
/// <summary>
/// 加密
/// </summary>
public static string Encode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
return strRet;
}
/// <summary>
/// 解密
/// </summary>
public static string Decode(string data)
{
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);
byte[] byEnc;
try
{
data.Replace("_%_", "/");
data.Replace("-%-", "#");
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
程序调用:
string password_code = Tool.Encode(password);
string a = password_code; // a=*&^%$ → 加密了
string password_encode = Tool.Decode(a);
string b = password_encode; // b=password → 解密了
拓展32位加密:
/// <summary>
/// 32位加密
/// </summary>
public static String Encrypt(String s)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
bytes = md5.ComputeHash(bytes);
md5.Clear();
string ret = "";
for (int i = 0; i < bytes.Length; i++)
{
ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
}
return ret.PadLeft(32, '0');
}
小结:
不断的制造bug中,我们才会渐渐的避免的bug。
不断的被别人坑,我们才渐渐不给别人挖坑。
站在这些巨人的肩膀上,会有更好的成长。