.NET常见的4种数据加密算法详解

0. 前言

在本文中,我们将介绍 .NET 的加密和解密功能。在 Web 应用程序中,用户的密码通常会使用 MD5 值作为密码数据存储。在其他情况下,也可能会使用加密和解密功能。

常见的加密算法分为对称加密和非对称加密。对称加密是指加密密钥和解密密钥相同,而非对称加密是加密密钥和解密密钥不同。

MD5 本质上不是加密算法,而是一种信息摘要算法。它将任意长度的数据转换为固定长度的数据。MD5 尽量保证了每个字符串最后计算出来的值都不一样,所以在密码保存中常用 MD5 做为保密值。

1. 信息摘要算法

这种算法严格意义上并不是加密算法,因为它是不可逆的。也就是说,一旦使用这种算法加密数据,就无法解密还原出原始数据。正是因为这种特性,它常常被用来保存密码。这样,即使有人获得了数据库和代码,也无法简单地推断出用户的密码。

1.1 MD5算法

MD5 信息摘要算法是一种被广泛使用的密码散列函数,它将任意长度的数据转换为固定长度的摘要,也称为哈希值。MD5 的摘要长度为 128 位(16 字节),用于确保信息传输的完整性。

具体实现:

using System;
using System.Security.Cryptography;
using System.Text;


public class MD5Helper
{


    public string Encrypt(string input)
    {


        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);


            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }


    }


}

2、常见对称加密算法

对称加密算法是指加密和解密使用相同的密钥进行运算。解密和加密是互逆的运算,因此对称加密算法的安全性取决于密钥的长度,密钥越长越安全。不过,密钥的长度也不宜过长,否则会影响加密和解密的速度。

接下来,我们将介绍常见的对称加密算法,以及 C# 实现方法。

2.1 DES 和 DESede 算法

DES 和 DESede 算法统称 DES 系列算法。DES 全称为 Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法。DESede 则是针对同一块数据做三次 DES 加密。

实现方式:

#region ========加密======== 


        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
    public static string Encrypt(string Text) 
    {
      return Encrypt(Text,"MATICSOFT");
    }
    /// <summary> 
    /// 加密数据 
    /// </summary> 
    /// <param name="Text"></param> 
    /// <param name="sKey"></param> 
    /// <returns></returns> 
    public static string Encrypt(string Text,string sKey) 
    { 
      DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
      byte[] inputByteArray; 
      inputByteArray=Encoding.Default.GetBytes(Text); 
      des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
      des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
      System.IO.MemoryStream ms=new System.IO.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); 
      } 
      return ret.ToString(); 
    } 


    #endregion


    #region ========解密======== 




        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
    public static string Decrypt(string Text) 
    {
      return Decrypt(Text,"MATICSOFT");
    }
    /// <summary> 
    /// 解密数据 
    /// </summary> 
    /// <param name="Text"></param> 
    /// <param name="sKey"></param> 
    /// <returns></returns> 
    public static string Decrypt(string Text,string sKey) 
    { 
      DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
      int len; 
      len=Text.Length/2; 
      byte[] inputByteArray = new byte[len]; 
      int x,i; 
      for(x=0;x<len;x++) 
      { 
        i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); 
        inputByteArray[x]=(byte)i; 
      } 
      des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
      des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
      System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
      CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); 
      cs.Write(inputByteArray,0,inputByteArray.Length); 
      cs.FlushFinalBlock(); 
      return Encoding.Default.GetString(ms.ToArray()); 
    } 


    #endregion

2.2 AES 加密算法

AES 算法是高级数据加密标准算法,旨在解决 DES 算法中的漏洞。AES 算法的核心是 Rijndael 算法。

具体的加解密实现:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;


public class AESHelper {


  public string Encrypt(string plainText, string key) {


    byte[] iv = new byte[16];
    byte[] array;


    using (Aes aes = Aes.Create()) {
      aes.Key = Encoding.UTF8.GetBytes(key);
      aes.IV = iv;


      ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);


      using (MemoryStream memoryStream = new MemoryStream()) {
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) {
          using (StreamWriter streamWriter = new StreamWriter(cryptoStream)) {
            streamWriter.Write(plainText);
          }


          array = memoryStream.ToArray();
        }
      }
    }


    return Convert.ToBase64String(array);
  }


  public string Decrypt(string cipherText, string key) {


    byte[] iv = new byte[16];
    byte[] buffer = Convert.FromBase64String(cipherText);


    using (Aes aes = Aes.Create()) {
      aes.Key = Encoding.UTF8.GetBytes(key);
      aes.IV = iv;
      ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);


      using (MemoryStream memoryStream = new MemoryStream(buffer)) {
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) {
          using (StreamReader streamReader = new StreamReader(cryptoStream)) {
            return streamReader.ReadToEnd();
          }
        }
      }
    }


  }


}

3.常见非对称加密算法

非对称加密算法是指加密密钥和解密密钥不同。非对称加密算法的密钥通常成对出现,分为公钥和私钥。公钥可以公开发布,而私钥需要保密。由于非对称加密算法的特性,无法通过公钥推导出私钥,反之亦然。

通常,非对称加密算法是用公钥进行加密,用私钥进行解密。

3.1 RSA 算法

RSA 算法是标准的非对称加密算法,由 Rivest、Shamir 和 Adleman 三人发明。RSA 算法是一种使用不同加密密钥和解密密钥的密码体制,其安全性取决于密钥的长度。1024 位的 RSA 密钥几乎不可能被破解。

具体实现:

using System;
using System.Security.Cryptography;
using System.Text;


public class RSAHelper {


  private string publicKey;
  private string privateKey;


  public RSAHelper(string publicKey, string privateKey) {
    this.publicKey = publicKey; 
    this.privateKey = privateKey;
  }


  public string Encrypt(string plainText) {


    var publicKeyBytes = Convert.FromBase64String(publicKey);


    using(var rsa = new RSACryptoServiceProvider(2048)) {
      rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);
      var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
      var cipherTextBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.Pkcs1);
      return Convert.ToBase64String(cipherTextBytes); 
    }


  }


  public string Decrypt(string cipherText) {


    var privateKeyBytes = Convert.FromBase64String(privateKey);  
    var rsa = new RSACryptoServiceProvider(2048);
    rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);


    var cipherBytes = Convert.FromBase64String(cipherText);
    var plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
    return Encoding.UTF8.GetString(plainTextBytes);


  }


}

因为RSA的特殊性,需要预先设置好公钥和私钥。C# 支持多种方式导入密钥,这里就不做过多介绍了。

4 总结

本文简单介绍了四种常用的加密算法的实现。其中,MD5 是最常用的加密算法,因为它被大多数系统用来保存密码。以上案例仅供参考,具体根据.NET的版本进行调整。

以上就是 .NET常见的四种数据加密算法的详细内容。有关 .NET 数据加密算法的更多资料,请关注本号的其他相关文章。

版权声明:本文来源于网友收集或网友供稿,仅供学习交流之用,如果有侵权,请转告小编或者留言,本公众号立即删除。

- EOF -

技术群:添加小编微信dotnet999

公众号:Dotnet讲堂

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值