您的位置:首页 > 其它

.NET中的加密解密:私钥加密(对称加密):DES

2010-03-09 14:40 507 查看
public class DesSample
{
DES des = null;

public DesSample(byte[] bKey)
{
des = new DESCryptoServiceProvider();
des.Key = bKey;
des.IV = bKey;
}

public string Encrypt(string data)
{
try
{
byte[] bData = Encoding.UTF8.GetBytes(data);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(bData, 0, bData.Length);
cs.FlushFinalBlock();

return Convert.ToBase64String(ms.ToArray());
}
catch
{
throw;
}
}

public string Decrypt(string data)
{
try
{
byte[] bData = Convert.FromBase64String(data);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(bData, 0, bData.Length);
cs.FlushFinalBlock();

return Encoding.UTF8.GetString(ms.ToArray());
}
catch
{
throw;
}
}

}//class DesSample

class Program
{
static void Main(string[] args)
{

byte[] bKey8 = UTF8Encoding.UTF8.GetBytes("12345678");
string data = "Hello,I am Jie.";

Console.WriteLine("Des Sample");
DesSample des = new DesSample(bKey8);
string desData = "";
desData = des.Encrypt(data);
Console.WriteLine("DES Encrypt:{0}", desData);
Console.WriteLine("DES Decrypt:{0}", des.Decrypt(desData));
Console.WriteLine();

Console.Read();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: