C# 实现3Des加密 解密

3Des对每个数据块进行了三次的DES加密算法,是DES的一个更安全的变形。比起最初的DES,3DES更为安全。

都是感觉一目了然的摘过来。

下面是加密解密的源码。ECB模式的。

 public class _3DESEncrypt
{ public static string Encrypt3DES(string a_strString, string a_strKey)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a_strKey, "md5").Substring(, ));
DES.Mode = CipherMode.ECB;
ICryptoTransform DESEncrypt = DES.CreateEncryptor();
byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(a_strString);
return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, , Buffer.Length));
} public static string Decrypt3DES(string a_strString, string a_strKey)
{
TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a_strKey, "md5").Substring(, ));
DES.Mode = CipherMode.ECB;
DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
ICryptoTransform DESDecrypt = DES.CreateDecryptor();
string result = "";
try
{
byte[] Buffer = Convert.FromBase64String(a_strString); result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, , Buffer.Length)); //MemoryStream msDecrypt = new MemoryStream(Buffer);
//CryptoStream csDecrypt = new CryptoStream(msDecrypt,
// DES.CreateDecryptor(DES.Key, DES.IV),
// CryptoStreamMode.Read); //// Create buffer to hold the decrypted data.
//byte[] fromEncrypt = new byte[Buffer.Length]; //// Read the decrypted data out of the crypto stream
//// and place it into the temporary buffer.
//csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
//result = System.Text.Encoding.Default.GetString(fromEncrypt);
}
catch (Exception e)
{
}
return result; }
}

里面加解密都是在DES的基础上实现、区别在于3Des的Key值是24位、DES而是8位。
DES的加密解密源码:http://www.cnblogs.com/tainshi/p/3501258.html

对于3DES算法的CBC模式、我是新人存在迷惑、解密出来的数据有乱码现象。大大们有这方面有关的文章、推荐给我喽。

上一篇:华为云亮相QCon2020深圳站,带你体会大厂的云原生玩法与秘诀


下一篇:Jdbc连接数据库基本步骤详解_java - JAVA