欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-13 12:20:04
本文实例为大家分享了.net使用rsa加密解密的具体代码,供大家参考,具体内容如下 passwordhelper.cs代码: using system;...

本文实例为大家分享了.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();

    }
  }
}

运行结果如图:

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

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

上一篇:

下一篇: