- UID
- 41172
注册时间2007-12-14
阅读权限30
最后登录1970-1-1
龙战于野
TA的每日心情 | 开心 2022-4-18 15:36 |
---|
签到天数: 207 天 [LV.7]常住居民III
|
楼主 |
发表于 2008-5-19 16:19:50
|
显示全部楼层
TripleDES算法
#region TripleDES算法
public class ClassTripleDES
{
public ClassTripleDES()
{
}
//加密,使用密码产生加密算法的公钥,并使用TripleDES对密码进行加密。
public static string Encrypt(string pass)
{
try
{
byte[] bt = (new System.Text.UnicodeEncoding()).GetBytes(pass);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(pass, null);
byte[] key = pdb.GetBytes(24);
byte[] iv = pdb.GetBytes(8);
MemoryStream ms = new MemoryStream();
TripleDESCryptoServiceProvider tdesc = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(ms,tdesc.CreateEncryptor(key, iv),CryptoStreamMode.Write);
cs.Write(bt, 0, bt.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch(Exception ex)
{
throw ex;
}
}
//解密,使用密码产生加密算法的公钥,并使用TripleDES对加密数据进行解密。
public static string Decrypt(string str, string pass)
{
try
{
byte[] bt = Convert.FromBase64String(str);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(pass, null);
byte[] key = pdb.GetBytes(24);
byte[] iv = pdb.GetBytes(8);
MemoryStream ms = new MemoryStream();
TripleDESCryptoServiceProvider tdesc = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(ms,tdesc.CreateDecryptor(key, iv),CryptoStreamMode.Write);
cs.Write(bt, 0, bt.Length);
cs.FlushFinalBlock();
return (new System.Text.UnicodeEncoding()).GetString(ms.ToArray());
}
catch(Exception ex)
{
throw ex;
}
}
//使用:
//string str = Encrypt("bbb");
//Console.WriteLine(Decrypt(str, "bbb"));
//加密,使用密码产生加密算法的公钥,并使用TripleDES对密码进行加密。
public static string EncryptWithKey(string pass, string p_key)
{
try
{
byte[] bt = (new System.Text.UnicodeEncoding()).GetBytes(pass);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(p_key, null);
byte[] key = pdb.GetBytes(24);
byte[] iv = pdb.GetBytes(8);
MemoryStream ms = new MemoryStream();
TripleDESCryptoServiceProvider tdesc = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(ms,tdesc.CreateEncryptor(key, iv),CryptoStreamMode.Write);
cs.Write(bt, 0, bt.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch(Exception ex)
{
throw ex;
}
}
//解密,使用密码产生加密算法的公钥,并使用TripleDES对加密数据进行解密。
public static string DecryptWithKey(string str, string p_key)
{
try
{
byte[] bt = Convert.FromBase64String(str);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(p_key, null);
byte[] key = pdb.GetBytes(24);
byte[] iv = pdb.GetBytes(8);
MemoryStream ms = new MemoryStream();
TripleDESCryptoServiceProvider tdesc = new TripleDESCryptoServiceProvider();
CryptoStream cs = new CryptoStream(ms,tdesc.CreateDecryptor(key, iv),CryptoStreamMode.Write);
cs.Write(bt, 0, bt.Length);
cs.FlushFinalBlock();
return (new System.Text.UnicodeEncoding()).GetString(ms.ToArray());
}
catch(Exception ex)
{
throw ex;
}
}
}
#endregion |
|