- 积分
- 10954
- 好友
- 记录
- 主题
- 帖子
- 听众
- 收听
|
发表于 2014-10-11 10:00:04
|
显示全部楼层
/// <summary>
/// 3DES加密
/// </summary>
/// <param name="Plaintext">明文</param>
/// <param name="KeyString">密钥</param>
/// <returns></returns>
internal static string Encrypt(string Plaintext, string KeyString)
{
try
{
byte[] Content = Encoding.UTF8.GetBytes(Plaintext);
byte[] EncryptKey = InitKey(KeyString);
using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
{
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.PKCS7;
//利用反射避开CLR的强制弱密钥判断
Type t = Type.GetType("System.Security.Cryptography.CryptoAPITransformMode");
object obj = t.GetField("Encrypt", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).GetValue(t);
MethodInfo mi = des.GetType().GetMethod("_NewEncryptor", BindingFlags.Instance | BindingFlags.NonPublic);
ICryptoTransform enCrypt = (ICryptoTransform)mi.Invoke(des, new object[] { EncryptKey, CipherMode.ECB, null, 0, obj });
MemoryStream stream = new MemoryStream();
CryptoStream encStream = new CryptoStream(stream, enCrypt, CryptoStreamMode.Write);
encStream.Write(Content, 0, Content.Length);
encStream.FlushFinalBlock();
return Convert.ToBase64String(stream.ToArray());
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 3DES解密
/// </summary>
/// <param name="Ciphertext">密文</param>
/// <param name="KeyString">密钥</param>
/// <returns></returns>
internal static string Decrypt(string Ciphertext, string KeyString)
{
try
{
byte[] buffer = Convert.FromBase64String(Ciphertext);
byte[] DecryptKey = InitKey(KeyString);
using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
{
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.PKCS7;
//利用反射避开CLR的强制弱密钥判断
Type t = Type.GetType("System.Security.Cryptography.CryptoAPITransformMode");
object obj = t.GetField("Decrypt", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).GetValue(t);
MethodInfo mi = des.GetType().GetMethod("_NewEncryptor", BindingFlags.Instance | BindingFlags.NonPublic);
ICryptoTransform deCrypt = (ICryptoTransform)mi.Invoke(des, new object[] { DecryptKey, CipherMode.ECB, null, 0, obj });
MemoryStream msDecrypt = new MemoryStream(buffer);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, deCrypt, CryptoStreamMode.Read);
byte[] fromDecrypt = new byte[buffer.Length];
csDecrypt.Read(fromDecrypt, 0, fromDecrypt.Length);
return Encoding.UTF8.GetString(fromDecrypt);
}
}
catch (Exception ex)
{
throw ex;
}
}
|
|