引入头文件:
using System.IO;
using System.Security.Cryptography;
以用户名为秘钥,对密码进行加密
主要代码
#region 加密字符串
///
/// 加密字符串
///
///
要加密的字符串
///
秘钥
///
加密后的字符串
string Encrypt(string str, string myKey)
{
string encryptKeyall = Convert.ToString(myKey); //定义密钥
if (encryptKeyall.Length < 9)
{
for (; ; )
{
if (encryptKeyall.Length < 9)
encryptKeyall += encryptKeyall;
else
break;
}
}
string encryptKey = encryptKeyall.Substring(0, 8);
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //实例化加/解密类对象
byte[] key = Encoding.UTF8.GetBytes(encryptKey); //定义字节数组,用来存储密钥
byte[] data = Encoding.UTF8.GetBytes(str);//定义字节数组,用来存储要加密的字符串
MemoryStream MStream = new MemoryStream(); //实例化内存流对象
//使用内存流实例化加密流对象
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length); //向加密流中写入数据
CStream.FlushFinalBlock(); //释放加密流
return Convert.ToBase64String(MStream.ToArray());//返回加密后的字符串
}
#endregion
#region 解密字符串
///
/// 解密字符串
///
///
要解密的字符串
///
秘钥
///
解密后的字符串
string Decrypt(string str, string myKey)
{
string encryptKeyall = Convert.ToString(myKey); //定义密钥
if (encryptKeyall.Length < 9)
{
for (; ; )
{
if (encryptKeyall.Length < 9)
encryptKeyall += encryptKeyall;
else
break;
}
}
string encryptKey = encryptKeyall.Substring(0, 8);
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //实例化加/解密类对象
byte[] key = Encoding.UTF8.GetBytes(encryptKey); //定义字节数组,用来存储密钥
byte[] data = Convert.FromBase64String(str);//定义字节数组,用来存储要解密的字符串
MemoryStream MStream = new MemoryStream(); //实例化内存流对象
//使用内存流实例化解密流对象
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length); //向解密流中写入数据
CStream.FlushFinalBlock(); //释放解密流
return Encoding.UTF8.GetString(MStream.ToArray()); //返回解密后的字符串
}
#endregion
加密算法指定键的大小对于此算法无效:是因为key值必须是8位64个字节,因此在输入时给予控制,注意key为Encoding.UTF8