现在一直在做一个小软件,公司的通讯录系统,也没什么功能增删改查,这算是我来这个公司实习的第一件事吧。
在修改个人信息的时候一直对于密码显示这个存在矛盾,不知道应该是要哪种形式去做,后来自己就先用md5加密的那种,做好了之后感觉不是很好,就是在去数据库密码的时候取不了,感觉特烦,后来在网上找了个可逆的加密,感觉好挺好用的。 先分享分享。
建一个类Encrypt保存加密解密的那些步骤。
private SymmetricAlgorithm mobjCryptoService;
private string Key; public Encrypt()
{
//
//TODO: 在此处添加构造函数逻辑
//
mobjCryptoService = new RijndaelManaged();
Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
}
/// <summary>
/// 获得密钥
/// </summary>
/// <returns>密钥</returns>
private byte[] GetLegalKey()
{
string sTemp = Key;
mobjCryptoService.GenerateKey();
byte[] bytTemp = mobjCryptoService.Key;
int KeyLength = bytTemp.Length; if (sTemp.Length > KeyLength)
sTemp = sTemp.Substring(, KeyLength);
else if (sTemp.Length < KeyLength)
sTemp = sTemp.PadRight(KeyLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>
/// 获得初始向量 IV
/// </summary>
/// <returns>初试向量IV</returns>
private byte[] GetLegalIV()
{
string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
mobjCryptoService.GenerateIV();
byte[] bytTemp = mobjCryptoService.IV;
int IVLength = bytTemp.Length;
if (sTemp.Length > IVLength)
sTemp = sTemp.Substring(, IVLength);
else if (sTemp.Length < IVLength)
sTemp = sTemp.PadRight(IVLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>
/// 加密方法
/// </summary>
/// <param name="Source">待加密的串</param>
/// <returns>经过加密的串</returns>
public string Encrypto(string Source)
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
MemoryStream ms = new MemoryStream();
mobjCryptoService.Key = GetLegalKey();
mobjCryptoService.IV = GetLegalIV();
ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn, , bytIn.Length);
cs.FlushFinalBlock();
ms.Close();
byte[] bytOut = ms.ToArray();
return Convert.ToBase64String(bytOut);
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="Source">待解密的串</param>
/// <returns>经过解密的串</returns>
public string Decrypto(string Source)
{
byte[] bytIn = Convert.FromBase64String(Source);
MemoryStream ms = new MemoryStream(bytIn, , bytIn.Length);
mobjCryptoService.Key = GetLegalKey();
mobjCryptoService.IV = GetLegalIV();
ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
转自:http://www.knowsky.com/442584.html
最后那个修改密码的,我就问主管应该怎么去显示,然后竟然得到的答案就是 ”为什么要去显示呢?“,好吧我承认我还小,最后我还是改回来了md5加密的。