/// <summary>
/// 自定义加密方法,该方法用来加密指定的字符串
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns>返回加密后的字符串</returns>
public string Encrypting(string str)
{
//把要加密的字符串存储到byte数组中
byte[] bytIn = System.Text.Encoding.Default.GetBytes(str);
//创建加密对象的密钥和初始化向量
byte[] iv = { 102, 16, 93, 156, 78, 4, 218, 32 };
byte[] key = { 55, 103, 246, 79, 36, 99, 167, 3 };
//创建DESC对象
DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
//设置密钥值
dsp.Key = iv;
//设置初始化向量值
dsp.IV = key;
//定义基本的加密转换运算 对称加密器对象
ICryptoTransform ict = dsp.CreateEncryptor();
//创建其支持存储区为内存的流
MemoryStream ms = new MemoryStream();
//定义将数据流链接到加密转换的流
CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String( ms.ToArray());
}
public string Decrypting(string str)
{
//把要解密的字符串存储到byte数组中
byte[] bytIn = System.Convert.FromBase64String(str);
//创建解密对象的密钥和初始化向量
byte[] iv = { 102, 16, 93, 156, 78, 4, 218, 32 };
byte[] key = { 55, 103, 246, 79, 36, 99, 167, 3 };
//创建DESC对象
DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
//设置密钥值
dsp.Key = iv;
//设置初始化向量值
dsp.IV = key;
//创建其支持存储区为内存的流
MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
//定义基本的解密转换运算 对称解密器对象
ICryptoTransform ict = dsp.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs, Encoding.Default);
return sr.ReadToEnd();
}
//获取用户详细信息,将密码,密码提示问题,密码提示答案通过自定义Encrypting方法加密
string pass =Encrypting(txtPass.Text);
protected void btnDecrypting_Click(object sender, EventArgs e)
{
//通过循环,调用Decrypting方法解密已被加密的数据
for (int i = 0; i < gvInfo.Rows.Count; i++)
{
gvInfo.Rows[i].Cells[1].Text = Decrypting(gvInfo.Rows[i].Cells[1].Text);
gvInfo.Rows[i].Cells[2].Text = Decrypting(gvInfo.Rows[i].Cells[2].Text);
gvInfo.Rows[i].Cells[3].Text = Decrypting(gvInfo.Rows[i].Cells[3].Text);
}
}