.net下几种常用的对称加解密

时间:2021-07-10 12:28:50

加密解密算法,太常用了,可是实在忍受不了十次八次之后还是要重头写,总是能告诉我原来的算法不好用(实际是压根不会用)的情况,不如直接写出来,再有人要直接给他看看,也顺便记录下算法,方便下新手大众。

DES算法:这算是大家非常常用的对称算法了,很多人都在用这个。

private static string DesKey = @"P@+#wG+Z";

/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string EncryptDES(string encryptString, string encryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch
{
return encryptString;
}
} /// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string DecryptDES(string decryptString, string decryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, , inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
}
DesKey 就是秘钥,这个看自己喜欢了,鄙人也曾经用过“wlyzdhp”之类的秘钥。

AES算法:也是常用的对称算法,安全系数比DES好一点。个人很推荐使用。

private static string AesKey = @")O[NB]6,YF}+efcaj{+oESb9d8>Z'e9M";

 /// <summary>
/// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
/// </summary>
/// <param name="EncryptString">待加密密文</param>
/// <param name="EncryptKey">加密密钥</param>
/// <returns></returns>
public static string AESEncrypt(string EncryptString, string EncryptKey)
{
if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); } string m_strEncrypt = ""; byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ=="); Rijndael m_AESProvider = Rijndael.Create(); try
{
byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString); MemoryStream m_stream = new MemoryStream(); CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write); m_csstream.Write(m_btEncryptString, , m_btEncryptString.Length); m_csstream.FlushFinalBlock(); m_strEncrypt = Convert.ToBase64String(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_csstream.Close(); m_csstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_AESProvider.Clear(); } return m_strEncrypt;
}
/// <summary>
/// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
/// </summary>
/// <param name="DecryptString">待解密密文</param>
/// <param name="DecryptKey">解密密钥</param>
/// <returns></returns>
public static string AESDecrypt(string DecryptString, string DecryptKey)
{
if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); } if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); } string m_strDecrypt = ""; byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ=="); Rijndael m_AESProvider = Rijndael.Create(); try
{
byte[] m_btDecryptString = Convert.FromBase64String(DecryptString); MemoryStream m_stream = new MemoryStream(); CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write); m_csstream.Write(m_btDecryptString, , m_btDecryptString.Length); m_csstream.FlushFinalBlock(); m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray()); m_stream.Close(); m_stream.Dispose(); m_csstream.Close(); m_csstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_AESProvider.Clear(); } return m_strDecrypt;
}

同上,不解释了。

RSA算法:RSA算法是用一套公钥秘钥进行加密解密的,从安全机制上来说比上面两种好,不过这种算法是基于两个大质数乘积互质原则来进行加密解密的,效率上跟公钥秘钥的大小有关,看官们可以根据情况适用,这里只给出了一套我现在常用的一套公钥秘钥,公钥秘钥网上有相关的生成软件,各位可以自行下载使用。

        /// <summary>
/// RSA加密
/// </summary>
/// <param name="publickey"></param>
/// <param name="content"></param>
/// <returns></returns>
public static string RSAEncrypt(string publickey, string content)
{
publickey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(publickey);
cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherbytes);
} /// <summary>
/// RSA解密
/// </summary>
/// <param name="privatekey"></param>
/// <param name="content"></param>
/// <returns></returns>
public static string RSADecrypt(string privatekey, string content)
{
privatekey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent><P>/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==</P><Q>6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==</Q><DP>ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==</DP><DQ>MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==</DQ><InverseQ>EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==</InverseQ><D>vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=</D></RSAKeyValue>";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] cipherbytes;
rsa.FromXmlString(privatekey);
cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherbytes);
}

总结:加密解密算法博大精深,这里只是为了我们使用起来方便,有现成的算法(即使这样依然有人敢告诉我这个方法不知道怎么调用)供我们快速调用,对于秘钥本身这里不做过多探讨了,有兴趣的我们可以过后研究交流。鄙人也是初涉加密解密领域,各种不足,各位看官轻喷。