110,536
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 加密函数
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">密匙,要求长度8位</param>
/// <returns>如果加密成功,返回加密后的字符串,失败则返回源串</returns>
public static string Encode(string encryptString, string encryptKey) //第一个参数是我准备加密的内容,第二个参数是我准备使用的加密密码(只能是8位,否则会报错)
{
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey);
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbKey), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
/// <summary>
/// 解密函数
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">密匙:内容加密的密匙,要求和加密函数中的密钥一致,才能解密</param>
/// <returns>解密后的内容</returns>
public static string Decode(string decryptString, string decryptKey)
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbKey), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
private void 加密_Click(object sender, EventArgs e)
{
string s_加密 = Encode("我喜欢","abdc1234"); //把"我喜欢"这几个字加密,使用的密码是abdc1234
string s1 = @"aa.dat";
using (StreamWriter sw = File.CreateText(s1))
{
sw.Write(s_加密); //把加密后的内容保存在文件中
}
}
private void 解密_Click(object sender, EventArgs e)
{
string s1 = @"aa.dat";
string s_解密后的内容 = "";
foreach (string s in File.ReadLines(s1, Encoding.UTF8)) //从文件中读取加密过的内容
{
s_解密后的内容 = Decode(s, "abdc1234"); //把读取的内容,进行解密。此处要求输入密钥
}
MessageBox.Show(s_解密后的内容);
}