/// <summary>
/// 完整
/// </summary>
public class TripleDESHelper1
{
public static string Encrypt(string aStrString, string aStrKey, CipherMode mode = CipherMode.ECB, string iv = "12345678")
{
try
{
var des = new TripleDESCryptoServiceProvider
{
Key = Encoding.UTF8.GetBytes(aStrKey.Substring(0, 24)),//長度必須24個字節(jié)
Mode = mode
};
if (mode == CipherMode.ECB)
{
des.IV = Encoding.UTF8.GetBytes(iv);
}
var desEncrypt = des.CreateEncryptor();
byte[] buffer = Encoding.UTF8.GetBytes(aStrString);
return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
}
catch (Exception e)
{
return string.Empty;
}
}
public static string Decrypt(string aStrString, string aStrKey, CipherMode mode = CipherMode.ECB, string iv = "12345678")
{
try
{
var des = new TripleDESCryptoServiceProvider
{
Key = Encoding.UTF8.GetBytes(aStrKey.Substring(0, 24)),//長度必須24個字節(jié)
Mode = mode,
Padding = PaddingMode.PKCS7
};
if (mode == CipherMode.CBC)
{
des.IV = Encoding.UTF8.GetBytes(iv);
}
var desDecrypt = des.CreateDecryptor();
var result = "";
byte[] buffer = Convert.FromBase64String(aStrString);
result = Encoding.UTF8.GetString(desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
return result;
}
catch (Exception e)
{
return string.Empty;
}
}
}
public class TripleDESHelper
{
static byte[] IV = Encoding.UTF8.GetBytes("12345678");
public static string Encrypt(string content, string key)
{
try
{
var tDes = new TripleDESCryptoServiceProvider
{
Key = Encoding.UTF8.GetBytes(key.Substring(0, 24)),//長度必須24個字節(jié)
Mode = CipherMode.ECB,
IV = IV
};
var desEncrypt = tDes.CreateEncryptor();
byte[] buffer = Encoding.UTF8.GetBytes(content);
return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
}
catch (Exception e)
{
return string.Empty;
}
}
public static string Decrypt(string content, string key)
{
try
{
var tDes = new TripleDESCryptoServiceProvider
{
Key = Encoding.UTF8.GetBytes(key.Substring(0, 24)),//長度必須24個字節(jié)
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
var desDecrypt = tDes.CreateDecryptor();
byte[] buffer = Convert.FromBase64String(content);
var result = Encoding.UTF8.GetString(desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
return result;
}
catch (Exception e)
{
return string.Empty;
}
}
} |