• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ASP.NET(C#)常用数据加密和解密方法2

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

上接:http://www.cnblogs.com/wifi/archive/2011/11/16/2250735.html

六、非对称加密之RSA加密和解密的讲解

  RSA公钥加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的。RSA取名来自开发他们三者的名字。RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的所有密码攻击,已被ISO推荐为公钥数据加密标准。RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作。

  RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一。RSA的安全性依赖于大数的因子分解,但并没有从理论上证明破译RSA的难度与大数分解难度等价。即RSA的重大缺陷是无法从理论上把握它的保密性能如何,而且密码学界多数人士倾向于因子分解不是NPC问题。

  RSA的缺点主要有:

  A)产生密钥很麻烦,受到素数产生技术的限制,因而难以做到一次一密。

  B)分组长度太大,为保证安全性,n 至少也要 600bits以上,使运算代价很高,尤其是速度较慢,较对称密码算法慢几个数量级;且随着大数分解技术的发展,这个

  长度还在增加,不利于数据格式的标准化。目前,SET(Secure Electronic Transaction)协议中要求CA采用2048bits长的密钥,其他实体使用1024比特的密钥。C)RSA密钥长度随着保密级别提高,增加很快。下表列出了对同一安全级别所对应的密钥长度。

  保密级别对称密钥长度(bit)RSA密钥长度(bit)ECC密钥长度(bit)保密年限

  808010241602010

  11211220482242030

  12812830722562040

  19219276803842080

  256256153605122120

  这种算法1978年就出现了,它是第一个既能用于数据加密也能用于数字签名的算法。它易于理解和操作,也很流行。算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman。早在1973年,英国国家通信总局的数学家Clifford Cocks就发现了类似的算法。但是他的发现被列为绝密,直到1998年才公诸于世。

  RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。

  RSA的算法涉及三个参数,n、e1、e2。

  其中,n是两个大质数p、q的积,n的二进制表示时所占用的位数,就是所谓的密钥长度。

  e1和e2是一对相关的值,e1可以任意取,但要求e1与(p-1)*(q-1)互质;再选择e2,要求(e2*e1)mod((p-1)*(q-1))=1。

  (n及e1),(n及e2)就是密钥对。

  RSA加解密的算法完全相同,设A为明文,B为密文,则:A=B^e1 mod n;B=A^e2 mod n;

  e1和e2可以互换使用,即:

  A=B^e2 mod n;B=A^e1 mod n;

 

  C#代码实现

  需引用using System.Security.Cryptography;

以下是代码片段:
  ///
  /// RSA加密
  ///
  ///
  ///
  ///
  public static string RSAEncrypt(string publickey, string content)
  {
  publickey = @"5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=AQAB";
  RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  byte[] cipherbytes;
  rsa.FromXmlString(publickey);
  cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
  return Convert.ToBase64String(cipherbytes);
  }
  ///
  /// RSA解密
  ///
  ///
  ///
  ///
  public static string RSADecrypt(string privatekey, string content)
  {
  privatekey = @"5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=AQAB
/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==
6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=";
  RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  byte[] cipherbytes;
  rsa.FromXmlString(privatekey);
  cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
  return Encoding.UTF8.GetString(cipherbytes);
  }

 

七、ASP.NET(C#)常用加密类调用的讲解

  1、C#常用加密解密类库代码如下:

 

以下是代码片段:
  ///
  /// MD5 加密静态方法
  ///
  /// 待加密的密文
  /// returns
  public static string MD5Encrypt(string EncryptString)
  {
  if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
  MD5 m_ClassMD5 = new MD5CryptoServiceProvider();
  string m_strEncrypt = "";
  try
  {
  m_strEncrypt = BitConverter.ToString(m_ClassMD5.ComputeHash(Encoding.Default.GetBytes(EncryptString))).Replace("-", "");
  }
  catch (ArgumentException ex) { throw ex; }
  catch (CryptographicException ex) { throw ex; }
  catch (Exception ex) { throw ex; }
  finally { m_ClassMD5.Clear(); }
  return m_strEncrypt;
  }
  ///
  /// DES 加密(数据加密标准,速度较快,适用于加密大量数据的场合)
  ///
  /// 待加密的密文
  /// 加密的密钥
  /// returns
  public static string DESEncrypt(string EncryptString, string EncryptKey)
  {
  if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
  if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
  if (EncryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
  byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  string m_strEncrypt = "";
  DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
  try
  {
  byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
  MemoryStream m_stream = new MemoryStream();
  CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
  m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
  m_cstream.FlushFinalBlock();
  m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
  m_stream.Close(); m_stream.Dispose();
  m_cstream.Close(); m_cstream.Dispose();
  }
  catch (IOException ex) { throw ex; }
  catch (CryptographicException ex) { throw ex; }
  catch (ArgumentException ex) { throw ex; }
  catch (Exception ex) { throw ex; }
  finally { m_DESProvider.Clear(); }
  return m_strEncrypt;
  }
  ///
  /// DES 解密(数据加密标准,速度较快,适用于加密大量数据的场合)
  ///
  /// 待解密的密文
  /// 解密的密钥
  /// returns
  public static string DESDecrypt(string DecryptString, string DecryptKey)
  {
  if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
  if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
  if (DecryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
  byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  string m_strDecrypt = "";
  DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
  try
  {
  byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
  MemoryStream m_stream = new MemoryStream();
  CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
  m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
  m_cstream.FlushFinalBlock();
  m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
  m_stream.Close(); m_stream.Dispose();
  m_cstream.Close(); m_cstream.Dispose();
  }
  catch (IOException ex) { throw ex; }
  catch (CryptographicException ex) { throw ex; }
  catch (ArgumentException ex) { throw ex; }
  catch (Exception ex) { throw ex; }
  finally { m_DESProvider.Clear(); }
  return m_strDecrypt;
  }
  ///
  /// RC2 加密(用变长密钥对大量数据进行加密)
  ///
  /// 待加密密文
  /// 加密密钥
  /// returns
  public static string RC2Encrypt(string EncryptString, string EncryptKey)
  {
  if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
  if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
  if (EncryptKey.Length < 5 || EncryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }
  string m_strEncrypt = "";
  byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();
  try
  {
  byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
  MemoryStream m_stream = new MemoryStream();
  CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
  m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
  m_cstream.FlushFinalBlock();
  m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
  m_stream.Close(); m_stream.Dispose();
  m_cstream.Close(); m_cstream.Dispose();
  }
  catch (IOException ex) { throw ex; }
  catch (CryptographicException ex) { throw ex; }
  catch (ArgumentException ex) { throw ex; }
  catch (Exception ex) { throw ex; }
  finally { m_RC2Provider.Clear(); }
  return m_strEncrypt;
  }
  ///
  /// RC2 解密(用变长密钥对大量数据进行加密)
  ///
  /// 待解密密文
  /// 解密密钥
  /// returns
  public static string RC2Decrypt(string DecryptString, string DecryptKey)
  {
  if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
  if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
  if (DecryptKey.Length < 5 || DecryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }
  byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  string m_strDecrypt = "";
  RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();
  try
  {
  byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
  MemoryStream m_stream = new MemoryStream();
  CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
  m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
  m_cstream.FlushFinalBlock();
  m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
  m_stream.Close(); m_stream.Dispose();
  m_cstream.Close(); m_cstream.Dispose();
  }
  catch (IOException ex) { throw ex; }
  catch (CryptographicException ex) { throw ex; }
  catch (ArgumentException ex) { throw ex; }
  catch (Exception ex) { throw ex; }
  finally { m_RC2Provider.Clear(); }
  return m_strDecrypt;
  }
  ///
  /// 3DES 加密(基于DES,对一块数据用三个不同的密钥进行三次加密,强度更高)
  ///
  /// 待加密密文
  /// 密钥一
  /// 密钥二
  /// 密钥三
  /// returns
  public static string DES3Encrypt(string EncryptString, string EncryptKey1, string EncryptKey2, string EncryptKey3)
  {
  string m_strEncrypt = "";
  try
  {
  m_strEncrypt = DESEncrypt(EncryptString, EncryptKey3);
  m_strEncrypt = DESEncrypt(m_strEncrypt, EncryptKey2);
  m_strEncrypt = DESEncrypt(m_strEncrypt, EncryptKey1);
  }
  catch (Exception ex) { throw ex; }
  return m_strEncrypt;
  }
  ///
  /// 3DES 解密(基于DES,对一块数据用三个不同的密钥进行三次加密,强度更高)
  ///
  /// 待解密密文
  /// 密钥一
  /// 密钥二
  /// 密钥三
  /// returns
  public static string DES3Decrypt(string DecryptString, string DecryptKey1, string DecryptKey2, string DecryptKey3)
  {
  string m_strDecrypt = "";
  try
  {
  m_strDecrypt = DESDecrypt(DecryptString, DecryptKey1);
  m_strDecrypt = DESDecrypt(m_strDecrypt, DecryptKey2);
  m_strDecrypt = DESDecrypt(m_strDecrypt, DecryptKey3);
  }
  catch (Exception ex) { throw ex; }
  return m_strDecrypt;
  }
  ///
  /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
  ///
  /// 待加密密文
  /// 加密密钥
  ///
  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, 0, 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;
  }
  ///
  /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
  ///
  /// 待解密密文
  /// 解密密钥
  ///
  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, 0, 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;
  }

  2、数据加密和解密简单代码调用如下:

以下是代码片段:
  Response.Write("
-----------MD5加密---------------
");
  Response.Write(SDKSecurity.MD5Encrypt("仰天一笑"));
  Response.Write("
-----------DES加密---------------
");
  Response.Write(SDKSecurity.DESEncrypt("仰天一笑", "anson-xu"));
  Response.Write("
-----------DES解密---------------
");
  Response.Write(SDKSecurity.DESDecrypt("l06JvJ45r/lb9iKzSXl47Q==", "anson-xu"));
  Response.Write("
-----------AES加密---------------
");
  Response.Write(SDKSecurity.AESEncrypt("仰天一笑", "ansonxuyu"));
  Response.Write("
-----------AES解密---------------
");
  Response.Write(SDKSecurity.AESDecrypt("avwKL+MO8+zoLHvzk0+TBA==", "ansonxuyu"));

  3、数据加密和解密调用后运行效果图如下:

 

转自:http://winsystem.ctocio.com.cn/378/12117878.shtml


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Asp.net使用jQuery实现数据绑定与分页发布时间:2022-07-10
下一篇:
ACE模板之JqgridAsp.NetMVC中使用ACE模板之Jqgrid发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap