.NET使用RSA加密解密的方法

本文实例为大家分享了.NET使用RSA加密解密的具体代码,供大家参考,具体内容如下

PassWordHelper.cs代码:

using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace Utils
{
  /// <summary>
  /// 密码加密解密操作相关类
  /// </summary>
  public static class PassWordHelper
  {
    #region MD5 加密

    /// <summary>
    /// MD5加密
    /// </summary>
    public static string Md532(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      MD5 md5 = MD5.Create();
      return HashAlgorithmBase(md5, source, encoding);
    }

    /// <summary>
    /// 加盐MD5加密
    /// </summary>
    public static string Md532Salt(this string source, string salt)
    {
      return string.IsNullOrEmpty(source) ? source.Md532() : (source + "『" + salt + "』").Md532();
    }

    #endregion

    #region SHA 加密

    /// <summary>
    /// SHA1 加密
    /// </summary>
    public static string Sha1(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      SHA1 sha1 = new SHA1CryptoServiceProvider();
      return HashAlgorithmBase(sha1, source, encoding);
    }

    /// <summary>
    /// SHA256 加密
    /// </summary>
    public static string Sha256(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      SHA256 sha256 = new SHA256Managed();
      return HashAlgorithmBase(sha256, source, encoding);
    }

    /// <summary>
    /// SHA512 加密
    /// </summary>
    public static string Sha512(this string source)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      SHA512 sha512 = new SHA512Managed();
      return HashAlgorithmBase(sha512, source, encoding);
    }

    #endregion

    #region HMAC 加密

    /// <summary>
    /// HmacSha1 加密
    /// </summary>
    public static string HmacSha1(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA1 hmacSha1 = new HMACSHA1(keyStr);
      return HashAlgorithmBase(hmacSha1, source, encoding);
    }

    /// <summary>
    /// HmacSha256 加密
    /// </summary>
    public static string HmacSha256(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA256 hmacSha256 = new HMACSHA256(keyStr);
      return HashAlgorithmBase(hmacSha256, source, encoding);
    }

    /// <summary>
    /// HmacSha384 加密
    /// </summary>
    public static string HmacSha384(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA384 hmacSha384 = new HMACSHA384(keyStr);
      return HashAlgorithmBase(hmacSha384, source, encoding);
    }

    /// <summary>
    /// HmacSha512 加密
    /// </summary>
    public static string HmacSha512(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACSHA512 hmacSha512 = new HMACSHA512(keyStr);
      return HashAlgorithmBase(hmacSha512, source, encoding);
    }

    /// <summary>
    /// HmacMd5 加密
    /// </summary>
    public static string HmacMd5(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACMD5 hmacMd5 = new HMACMD5(keyStr);
      return HashAlgorithmBase(hmacMd5, source, encoding);
    }

    /// <summary>
    /// HmacRipeMd160 加密
    /// </summary>
    public static string HmacRipeMd160(this string source, string keyVal)
    {
      if (string.IsNullOrEmpty(source)) return null;
      var encoding = Encoding.UTF8;
      byte[] keyStr = encoding.GetBytes(keyVal);
      HMACRIPEMD160 hmacRipeMd160 = new HMACRIPEMD160(keyStr);
      return HashAlgorithmBase(hmacRipeMd160, source, encoding);
    }

    #endregion

    #region AES 加密解密

    /// <summary>
    /// AES加密
    /// </summary>
    /// <param name="source">待加密字段</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static string AesStr(this string source, string keyVal, string ivVal)
    {
      var encoding = Encoding.UTF8;
      byte[] btKey = keyVal.FormatByte(encoding);
      byte[] btIv = ivVal.FormatByte(encoding);
      byte[] byteArray = encoding.GetBytes(source);
      string encrypt;
      Rijndael aes = Rijndael.Create();
      using (MemoryStream mStream = new MemoryStream())
      {
        using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write))
        {
          cStream.Write(byteArray, 0, byteArray.Length);
          cStream.FlushFinalBlock();
          encrypt = Convert.ToBase64String(mStream.ToArray());
        }
      }
      aes.Clear();
      return encrypt;
    }

    /// <summary>
    /// AES解密
    /// </summary>
    /// <param name="source">待加密字段</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static string UnAesStr(this string source, string keyVal, string ivVal)
    {
      var encoding = Encoding.UTF8;
      byte[] btKey = keyVal.FormatByte(encoding);
      byte[] btIv = ivVal.FormatByte(encoding);
      byte[] byteArray = Convert.FromBase64String(source);
      string decrypt;
      Rijndael aes = Rijndael.Create();
      using (MemoryStream mStream = new MemoryStream())
      {
        using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write))
        {
          cStream.Write(byteArray, 0, byteArray.Length);
          cStream.FlushFinalBlock();
          decrypt = encoding.GetString(mStream.ToArray());
        }
      }
      aes.Clear();
      return decrypt;
    }

    /// <summary>
    /// AES Byte类型 加密
    /// </summary>
    /// <param name="data">待加密明文</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static byte[] AesByte(this byte[] data, string keyVal, string ivVal)
    {
      byte[] bKey = new byte[32];
      Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
      byte[] bVector = new byte[16];
      Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
      byte[] cryptograph;
      Rijndael aes = Rijndael.Create();
      try
      {
        using (MemoryStream mStream = new MemoryStream())
        {
          using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write))
          {
            cStream.Write(data, 0, data.Length);
            cStream.FlushFinalBlock();
            cryptograph = mStream.ToArray();
          }
        }
      }
      catch
      {
        cryptograph = null;
      }
      return cryptograph;
    }

    /// <summary>
    /// AES Byte类型 解密
    /// </summary>
    /// <param name="data">待解密明文</param>
    /// <param name="keyVal">密钥值</param>
    /// <param name="ivVal">加密辅助向量</param>
    /// <returns></returns>
    public static byte[] UnAesByte(this byte[] data, string keyVal, string ivVal)
    {
      byte[] bKey = new byte[32];
      Array.Copy(Encoding.UTF8.GetBytes(keyVal.PadRight(bKey.Length)), bKey, bKey.Length);
      byte[] bVector = new byte[16];
      Array.Copy(Encoding.UTF8.GetBytes(ivVal.PadRight(bVector.Length)), bVector, bVector.Length);
      byte[] original;
      Rijndael aes = Rijndael.Create();
      try
      {
        using (MemoryStream mStream = new MemoryStream(data))
        {
          using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read))
          {
            using (MemoryStream originalMemory = new MemoryStream())
            {
              byte[] buffer = new byte[1024];
              int readBytes;
              while ((readBytes = cStream.Read(buffer, 0, buffer.Length)) > 0)
              {
                originalMemory.Write(buffer, 0, readBytes);
              }

              original = originalMemory.ToArray();
            }
          }
        }
      }
      catch
      {
        original = null;
      }
      return original;
    }

    #endregion

    #region RSA 加密解密

    //密钥对,请配合密钥生成工具使用『 http://download.csdn.net/detail/downiis6/9464639 』
    private const string PublicRsaKey = @"<RSAKeyValue>
 <Modulus>8Yvf/LjXRhCuOREk2CuSYvbD/RadwJ4sjHREIpQVKwkTlG3BtRgpnaMcoeLAesmwvpBWnqK4hBkYLxhRj+NEKnlGrJ+LkNMnZr0/4CMuulZFAnx7iQYaSq7Eh7kBKGLofc05CjZguYpnPNxHIv4VNx+a9tIh+hnhjrmkJLUm3l0=</Modulus>
 <Exponent>AQAB</Exponent>
</RSAKeyValue>";
    private const string PrivateRsaKey = @"<RSAKeyValue>
 <Modulus>8Yvf/LjXRhCuOREk2CuSYvbD/RadwJ4sjHREIpQVKwkTlG3BtRgpnaMcoeLAesmwvpBWnqK4hBkYLxhRj+NEKnlGrJ+LkNMnZr0/4CMuulZFAnx7iQYaSq7Eh7kBKGLofc05CjZguYpnPNxHIv4VNx+a9tIh+hnhjrmkJLUm3l0=</Modulus>
 <Exponent>AQAB</Exponent>
 <P>/xAaa/4dtDxcEAk5koSZBPjuxqvKJikpwLA1nCm3xxAUMDVxSwQyr+SHFaCnBN9kqaNkQCY6kDCfJXFWPOj0Bw==</P>
 <Q>8m8PFVA4sO0oEKMVQxt+ivDTHFuk/W154UL3IgC9Y6bzlvYewXZSzZHmxZXXM1lFtwoYG/k+focXBITsiJepew==</Q>
 <DP>ONVSvdt6rO2CKgSUMoSfQA9jzRr8STKE3i2lVG2rSIzZosBVxTxjOvQ18WjBroFEgdQpg23BQN3EqGgvqhTSQw==</DP>
 <DQ>gfp7SsEM9AbioTDemHEoQlPly+FyrxE/9D8UAt4ErGX5WamxSaYntOGRqcOxcm1djEpULMNP90R0Wc7uhjlR+w==</DQ>
 <InverseQ>C0eBsp2iMOxWwKo+EzkHOP0H+YOitUVgjekGXmSt9a3TvikQNaJ5ATlqKsZaMGsnB6UIHei+kUaCusVX0HgQ2A==</InverseQ>
 <D>tPYxEfo9Nb3LeO+SJe3G1yO+w37NIwCdqYB1h15f2YUMSThNVmpKy1HnYpUp1RQDuVETw/duu3C9gJL8kAsZBjBrVZ0zC/JZsgvSNprfUK3Asc4FgFsGfQGKW1nvvgdMbvqr4ClB0R8czkki+f9Oc5ea/RMqXxlI+XjzMYDEknU=</D>
</RSAKeyValue>";

    /// <summary>
    /// RSA 加密
    /// </summary>
    public static string Rsa(this string source)
    {
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      rsa.FromXmlString(PublicRsaKey);
      var cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(source), true);
      return Convert.ToBase64String(cipherbytes);
    }

    /// <summary>
    /// RSA解密
    /// </summary>
    public static string UnRsa(this string source)
    {
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      rsa.FromXmlString(PrivateRsaKey);
      var cipherbytes = rsa.Decrypt(Convert.FromBase64String(source), true);
      return Encoding.UTF8.GetString(cipherbytes);
    }

    #endregion

    #region DES 加密解密

    /// <summary>
    /// DES 加密
    /// </summary>
    public static string Des(this string source, string keyVal, string ivVal)
    {
      try
      {
        byte[] data = Encoding.UTF8.GetBytes(source);
        var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
        var desencrypt = des.CreateEncryptor();
        byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
        return BitConverter.ToString(result);
      }
      catch { return "转换出错!"; }
    }

    /// <summary>
    /// DES 解密
    /// </summary>
    public static string UnDes(this string source, string keyVal, string ivVal)
    {
      try
      {
        string[] sInput = source.Split("-".ToCharArray());
        byte[] data = new byte[sInput.Length];
        for (int i = 0; i < sInput.Length; i++)
        {
          data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber);
        }
        var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(keyVal.Length > 8 ? keyVal.Substring(0, 8) : keyVal), IV = Encoding.ASCII.GetBytes(ivVal.Length > 8 ? ivVal.Substring(0, 8) : ivVal) };
        var desencrypt = des.CreateDecryptor();
        byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
        return Encoding.UTF8.GetString(result);
      }
      catch { return "解密出错!"; }
    }

    #endregion

    #region TripleDES 加密解密

    /// <summary>
    /// DES3 加密
    /// </summary>
    public static string Des3(this string source, string keyVal)
    {
      try
      {
        TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
        {
          Key = keyVal.FormatByte(Encoding.UTF8),
          Mode = CipherMode.ECB,
          Padding = PaddingMode.PKCS7
        };
        using (MemoryStream ms = new MemoryStream())
        {
          byte[] btArray = Encoding.UTF8.GetBytes(source);
          try
          {
            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
              cs.Write(btArray, 0, btArray.Length);
              cs.FlushFinalBlock();
            }
            return ms.ToArray().Bytes2Str();
          }
          catch { return source; }
        }
      }
      catch
      {
        return "TripleDES加密出现错误";
      }
    }

    /// <summary>
    /// DES3 解密
    /// </summary>
    public static string UnDes3(this string source, string keyVal)
    {
      try
      {
        byte[] byArray = source.Str2Bytes();
        TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
        {
          Key = keyVal.FormatByte(Encoding.UTF8),
          Mode = CipherMode.ECB,
          Padding = PaddingMode.PKCS7
        };
        using (MemoryStream ms = new MemoryStream())
        {
          using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
          {
            cs.Write(byArray, 0, byArray.Length);
            cs.FlushFinalBlock();
            cs.Close();
            ms.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
          }
        }
      }
      catch
      {
        return "TripleDES解密出现错误";
      }
    }

    #endregion

    #region BASE64 加密解密

    /// <summary>
    /// BASE64 加密
    /// </summary>
    /// <param name="source">待加密字段</param>
    /// <returns></returns>
    public static string Base64(this string source)
    {
      var btArray = Encoding.UTF8.GetBytes(source);
      return Convert.ToBase64String(btArray, 0, btArray.Length);
    }

    /// <summary>
    /// BASE64 解密
    /// </summary>
    /// <param name="source">待解密字段</param>
    /// <returns></returns>
    public static string UnBase64(this string source)
    {
      var btArray = Convert.FromBase64String(source);
      return Encoding.UTF8.GetString(btArray);
    }

    #endregion

    #region 内部方法

    /// <summary>
    /// 转成数组
    /// </summary>
    private static byte[] Str2Bytes(this string source)
    {
      source = source.Replace(" ", "");
      byte[] buffer = new byte[source.Length / 2];
      for (int i = 0; i < source.Length; i += 2) buffer[i / 2] = Convert.ToByte(source.Substring(i, 2), 16);
      return buffer;
    }

    /// <summary>
    /// 转换成字符串
    /// </summary>
    private static string Bytes2Str(this IEnumerable<byte> source, string formatStr = "{0:X2}")
    {
      StringBuilder pwd = new StringBuilder();
      foreach (byte btStr in source) { pwd.AppendFormat(formatStr, btStr); }
      return pwd.ToString();
    }

    private static byte[] FormatByte(this string strVal, Encoding encoding)
    {
      return encoding.GetBytes(strVal.Base64().Substring(0, 16).ToUpper());
    }

    /// <summary>
    /// HashAlgorithm 加密统一方法
    /// </summary>
    private static string HashAlgorithmBase(HashAlgorithm hashAlgorithmObj, string source, Encoding encoding)
    {
      byte[] btStr = encoding.GetBytes(source);
      byte[] hashStr = hashAlgorithmObj.ComputeHash(btStr);
      return hashStr.Bytes2Str();
    }

    #endregion
  }
}

Program.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {

      string plainText = "这是一条被和谐的消息!";
      //加密明文,获得密文
      string EncryptText= Utils.PassWordHelper.Rsa(plainText);
      Console.WriteLine(EncryptText);

      //解密密文,获得明文
      string DecryptText = Utils.PassWordHelper.UnRsa(EncryptText);
      Console.WriteLine(DecryptText);
      Console.ReadKey();

    }
  }
}

运行结果如图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • asp.net下XML的加密和解密实现方法

    介绍 我们有3个加密xml的方法 1.仅仅使用对称加密的方法加密xml 这种加密方法只使用一个密钥,也就是说无论是加密xml还是解密xml都使用一个相同的密钥.因为这个密钥不会在被加密的xml中保存,所以我们需要在加密和解密的过程中加载这个密钥并保护它不被窃取. 2.使用对称加密和非对称加密相结合的方法来加密xml 这种方法需要一个用于加密数据的对称密钥和一个用于保护这个对称密钥的非对称密钥.被加密的对称密钥和被加密的数据一起保存在xml文档中.当用私有非对称密钥解密密钥的时候要用公开非对称密钥

  • 在ASP.Net中实现RSA加密的方法

    在我们实际运用中,加密是保证数据安全的重要手段.以前使用ASP时,对数据加密可以使用MD5和SHA1算法,这两种算法虽然快捷有效,但是无法对通过它们加密的密文进行反运算,即是解密.因此需要解密数据的场合,这两种方法就不太适合了.当然你也可以自己编写适用的加密和解密程序,不过这对编写者的数学水平有很高的要求,一般人是很难做到的. 现在,随着ASP.Net的推出,彻底改变了以前ASP下的编程模式.我们能够利用.Net Framework中的类提供的加密服务来保证数据安全.目前应用较为广泛的加密方法是

  • asp.net的加密解密技巧

    对于加密和解密,我们都知道.下面主要介绍的是ASP.NET中的加密和解密. 一.数据加密/编码算法列表 常见用于保证安全的加密或编码算法如下: 1.常用密钥算法 密钥算法用来对敏感数据.摘要.签名等信息进行加密,常用的密钥算法包括: DES(Data Encryption Standard):数据加密标准,速度较快,适用于加密大量数据的场合: 3DES(Triple DES):是基于DES,对一块数据用三个不同的密钥进行三次加密,强度更高: RC2和 RC4:用变长密钥对大量数据进行加密,比 D

  • asp.net 对中文汉字的加密与解密代码

    复制代码 代码如下: protected void Page_Load(object sender, EventArgs e) { //加密算法 string username = "我是陈建勇"; //MD5加密 - 得到32位加密数据,数据不好解密.过于复杂. username =FormsAuthentication.HashPasswordForStoringInConfigFile(username, "MD5"); //SHA1加密 - 得到40位加密数

  • asp.net 字符串加密解密技术

    复制代码 代码如下: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Syste

  • asp.net TripleDES加密、解密算法

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace WindowsFormsApplication1 { #region TripleDES算法 public class ClassTripleDES { public ClassTripleDES()

  • asp.net web.config加密解密方法

    使用命令行工具aspnet_regiis.exe 你还能够使用aspnet_regiis.exe命令行工具来加密和解密Web.config文件配置部分,你可以在"%WINDOWSDIR%\Microsoft.Net\Framework\version"目录下找到这个工具.为了加密Web.config文件中的一个节,你可以在这个命令行工具中使用DPAPI机器密钥,如下所示: 加密一个特定网站的Web.config文件的通用形式: 复制代码 代码如下: aspnet_regiis.exe

  • asp.net实现的MD5加密和DES加解密算法类完整示例

    本文实例讲述了asp.net实现的MD5加密和DES加解密算法类.分享给大家供大家参考,具体如下: #region MD5算法 public string md5(string str, int code) { if (code == 32) //32位加密 { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower(); } else /

  • .net调用JScript脚本及JS url加密解密

    .net 使用escape 和 unescape方法: 在 C# 里,使用 escape 和 unescape,添加引用: Microsoft.JScript string strEscaped = Microsoft.JScript.GlobalObject.escape("测试打"); 注意:js的一些函数,在 jscript.net 里,全部放在 GlobalObject 下 同样, 就可以使用 unescape, encodeURI, decodeURI 等等的函数了. 或者S

  • 解析Asp.net,C# 纯数字加密解密字符串的应用

    继上篇:Asp.net,C# 加密解密字符串的使用详解,有网友提问: 也就是说加密后的数据不再是:N8lAaHMFtSAQgaf3+RUFng== 希望encryptedString是"120387789370480938409832840923492384028934-"; 当然上面的数字是我随便乱敲的. 那么如何实现纯数字呢?? 想法很简单,只要将字符变成Ascll 码就可以了.例如a:97, =:61; 那么encryptedString 就可以变成 97 81 61 33 44

  • Asp.net,C# 加密解密字符串的使用详解

    首先在web.config | app.config 文件下增加如下代码: 复制代码 代码如下: <?xml version="1.0"?>  <configuration>    <appSettings>      <add key="IV" value="SuFjcEmp/TE="/>      <add key="Key" value="KIPSToILG

随机推荐