2021-07-23

C#常用的加密算法:MD5、Base64、SHA1、SHA256、HmacSHA256、DES、AES、RSA

RSA生成C#的

目录
  • 简介
  • 需要引用的类
  • 一、MD5加密
  • 二、Base64加码解码
  • 三、SHA加密解密
  • 四、HmacSHA256 Base64加密
  • 五、DES加密解密
  • 六、AES加密解密
  • 七、RSA加密解密:采用公钥,私钥的模式

简介

本文主要讲解一下C#常用的那些加密算法,包括MD5、Base64、SHA1、SHA256、HmacSHA256、DES、AES、RSA加密等,有需要的朋友可以参考下

需要引用的类

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

还需要安装 BouncyCastle
在菜单栏找到 工具 —> NuGet 包管理器 —> 管理解决方案的NuGet程序包 —> 浏览 —> 搜索 "BouncyCastle" —> 安装

我自己定义的公共字段;有需要的朋友可以自行定义

  private static CspParameters Param;  /// <summary>  /// SK(Secret Access Key):与访问密钥ID结合使用的密钥,对请求进行加密签名,可标识发送方,并防止请求被修改  /// </summary>  public static string _appSecret = ConfigurationManager.AppSettings["appSecret"].ToString();  /// <summary>  /// AK(Access Key ID):访问密钥ID。与私有访问密钥关联的唯一标识符;访问密钥ID和私有访问密钥一起使用,对请求进行加密签名  /// </summary>  public static string _appKey = ConfigurationManager.AppSettings["appKey"].ToString();  /// <summary>  /// DES密钥  /// </summary>  private static byte[] _KEY = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };  /// <summary>  /// DES向量  /// </summary>  private static byte[] _IV = new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };  /// <summary>  /// RSA加密/解密的默认公钥  /// </summary>  private static string _publicKey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";  /// <summary>  /// RSA解密/加密的默认私钥  /// </summary>  private static string _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>";  /// <summary>  /// 8位加密密钥  /// </summary>  private static string keys = "olikjhgb";  /// <summary>  /// 16位的加密秘钥  /// </summary>  private static string Key = "1123uyrlouhd@_Lq";  /// <summary>  /// 16位以上的默认向量  /// </summary>  private static string vector = "*abcdefghijklmnopqrst@";

一、MD5加密

  • MD5加密是最常见的加密方式,因为MD5是不可逆的,所以很多系统的密码都是用MD5加密保存的。
  • 虽说MD5加密不可逆,但是我们可以对明文再次加密,进行两次加密的密文进行对比
  #region MD5加密解密  /// <summary>  /// 16位MD5加密  /// </summary>  /// <param name="laws">需要加密的明文字符串</param>  /// <returns></returns>  public static string MD5Encrypt16(string laws)  {   var md5 = new MD5CryptoServiceProvider();   string cipherText = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(laws)), 4, 8);   cipherText = cipherText.Replace("-", "");   return cipherText;  }  /// <summary>  /// 32位MD5加密  /// </summary>  /// <param name="laws">需要加密的明文字符串</param>  /// <returns>32位MD5加密密文字符串</returns>  public static string MD5Encrypt32(string laws)  {   string plainText = laws;   string rule = "";   MD5 md5 = MD5.Create(); //实例化一个md5对像         // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(plainText));   // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得   for (int i = 0; i < s.Length; i++)   {    // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符     rule = rule + s[i].ToString("x2");   }   return rule;  }  /// <summary>  /// 64位MD5加密  /// </summary>  /// <param name="laws">需要加密的明文字符串</param>  /// <returns>64位MD5加密密文字符串</returns>  public static string MD5Encrypt64(string laws)  {   string rule = laws;   MD5 md5 = MD5.Create(); //实例化一个md5对像   // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(rule));   return Convert.ToBase64String(s);  }  /// <summary>  /// 对字符串进MD5加密  /// </summary>  /// <param name="sourceStr">源类型</param>  /// <returns>加密后字符串</returns>  public static string Md5Encrypt(string sourceStr)  {   MD5 md5 = new MD5CryptoServiceProvider();   //将要加密的字符串转换成字节数组   byte[] palindata = Encoding.Default.GetBytes(sourceStr);   //通过字节数组进行加密   byte[] encryptdata = md5.ComputeHash(palindata);   //将加密后的字节数组转换成字符串   string returnData = Convert.ToBase64String(encryptdata);   return returnData;  }  /// <summary>  /// Md5密钥加密  /// </summary>  /// <param name="pToEncrypt">要加密的string字符串</param>  /// <returns></returns>  public static string Md5Encrypt_Key(string pToEncrypt)  {   DESCryptoServiceProvider des = new DESCryptoServiceProvider();   byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);   des.Key = Encoding.ASCII.GetBytes(keys);   des.IV = Encoding.ASCII.GetBytes(keys);   MemoryStream ms = new MemoryStream();   CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);   cs.Write(inputByteArray, 0, inputByteArray.Length);   cs.FlushFinalBlock();   StringBuilder ret = new StringBuilder();   foreach (byte b in ms.ToArray())   {    ret.AppendFormat("{0:X2}", b);   }   var s = ret.ToString();   return s;  }  /// <summary>  /// Md5解密  /// </summary>  /// <param name="pToDecrypt">解密string</param>  /// <returns></returns>  public static string Md5Decrypt(string pToDecrypt)  {   DESCryptoServiceProvider des = new DESCryptoServiceProvider();   byte[] inputByteArray = new byte[pToDecrypt.Length / 2];   for (int x = 0; x < pToDecrypt.Length / 2; x++)   {    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));    inputByteArray[x] = (byte)i;   }   des.Key = Encoding.ASCII.GetBytes(_appSecret);   des.IV = Encoding.ASCII.GetBytes(_appSecret);   MemoryStream ms = new MemoryStream();   CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);   cs.Write(inputByteArray, 0, inputByteArray.Length);   cs.FlushFinalBlock();   return Encoding.Default.GetString(ms.ToArray());  }  /// <summary>  /// MD5流加密  /// </summary>  /// <param name="inputStream">输入流</param>  /// <returns></returns>  public static string GenerateMD5(Stream inputStream)  {   using (MD5 mi = MD5.Create())   {    //开始加密    byte[] newBuffer = mi.ComputeHash(inputStream);    StringBuilder sb = new StringBuilder();    for (int i = 0; i < newBuffer.Length; i++)    {     sb.Append(newBuffer[i].ToString("x2"));    }    return sb.ToString();   }  }

No comments:

Post a Comment