zoukankan      html  css  js  c++  java
  • C#几种常用的加密方式

    一、AES加密算法
       AES算法基于排列和置换运算。排列是对数据重新进行安排,置换是将一个数据单元替换为另一个。AES 使用几种不同的方法来执行排列和置换运算。 
       AES是一个迭代的、对称密钥分组的密码,它可以使用128、192 和 256 位密钥,并且用 128 位(16字节)分组加密和解密数据。与公共密钥密码使用密钥对不同,对称密钥密码使用相同的密钥加密和解密数据。通过分组密码返回的加密数据的位数与输入数据相同。迭代加密使用一个循环结构,在该循环中重复置换和替换输入数据。 摘自:互动百科

           几种模式的优缺点对比:

          

    C#代码:

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

    namespace PwdDemo
    {
    public class AESHelper
    {
    /// <summary>
    /// AES 加密
    /// </summary>
    /// <param name="str">明文(待加密)</param>
    /// <param name="key">密文</param>
    /// <returns></returns>
    public string AesEncrypt(string str, string key)
    {
    if (string.IsNullOrEmpty(str)) return null;
    Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

    RijndaelManaged rm = new RijndaelManaged
    {
    Key = Encoding.UTF8.GetBytes(key),
    Mode = CipherMode.ECB,
    Padding = PaddingMode.PKCS7
    };

    ICryptoTransform cTransform = rm.CreateEncryptor();
    Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
    return Convert.ToBase64String(resultArray);
    }

    /// <summary>
    /// AES 解密
    /// </summary>
    /// <param name="str">明文(待解密)</param>
    /// <param name="key">密文</param>
    /// <returns></returns>
    public string AesDecrypt(string str, string key)
    {
    if (string.IsNullOrEmpty(str)) return null;
    Byte[] toEncryptArray = Convert.FromBase64String(str);

    RijndaelManaged rm = new RijndaelManaged
    {
    Key = Encoding.UTF8.GetBytes(key),
    Mode = CipherMode.ECB,
    Padding = PaddingMode.PKCS7
    };

    ICryptoTransform cTransform = rm.CreateDecryptor();
    Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    return Encoding.UTF8.GetString(resultArray);
    }
    }
    }
    二、DES加密算法
            DES设计中使用了分组密码设计的两个原则:混淆(confusion)和扩散(diffusion),其目的是抗击敌手对密码系统的统计分析。混淆是使密文的统计特性与密钥的取值之间的关系尽可能复杂化,以使密钥和明文以及密文之间的依赖性对密码分析者来说是无法利用的。扩散的作用就是将每一位明文的影响尽可能迅速地作用到较多的输出密文位中,以便在大量的密文中消除明文的统计结构,并且使每一位密钥的影响尽可能迅速地扩展到较多的密文位中,以防对密钥进行逐段破译。

    C#代码:

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

    namespace PwdDemo
    {
    public class DESHelper
    {
    //密钥
    public static byte[] _KEY = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
    //向量
    public static byte[] _IV = new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };

    /// <summary>
    /// DES加密操作
    /// </summary>
    /// <param name="normalTxt"></param>
    /// <returns></returns>
    public string DesEncrypt(string normalTxt)
    {
    //byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);
    //byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);

    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    int i = cryptoProvider.KeySize;
    MemoryStream ms = new MemoryStream();
    CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(_KEY, _IV), CryptoStreamMode.Write);

    StreamWriter sw = new StreamWriter(cst);
    sw.Write(normalTxt);
    sw.Flush();
    cst.FlushFinalBlock();
    sw.Flush();

    string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
    return strRet;
    }

    /// <summary>
    /// DES解密操作
    /// </summary>
    /// <param name="securityTxt">加密字符串</param>
    /// <returns></returns>
    public string DesDecrypt(string securityTxt)//解密
    {
    //byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY);
    //byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV);
    byte[] byEnc;
    try
    {
    securityTxt.Replace("_%_", "/");
    securityTxt.Replace("-%-", "#");
    byEnc = Convert.FromBase64String(securityTxt);
    }
    catch
    {
    return null;
    }
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    MemoryStream ms = new MemoryStream(byEnc);
    CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(_KEY, _IV), CryptoStreamMode.Read);
    StreamReader sr = new StreamReader(cst);
    return sr.ReadToEnd();
    }
    }
    }
     

    三、RSA加密算法
            RSA是第一个能同时用于加密和数字签名的算法,也易于理解和操作。RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一。

    C#代码:

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

    namespace PwdDemo
    {
    public class RSAHelper
    {
    private const int RsaKeySize = 2048;
    private const string publicKeyFileName = "RSA.Pub";
    private const string privateKeyFileName = "RSA.Private";

    /// <summary>
    ///在给定路径中生成XML格式的私钥和公钥。
    /// </summary>
    public void GenerateKeys(string path)
    {
    using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
    {
    try
    {
    // 获取私钥和公钥。
    var publicKey = rsa.ToXmlString(false);
    var privateKey = rsa.ToXmlString(true);

    // 保存到磁盘
    File.WriteAllText(Path.Combine(path, publicKeyFileName), publicKey);
    File.WriteAllText(Path.Combine(path, privateKeyFileName), privateKey);

    //Console.WriteLine(string.Format("生成的RSA密钥的路径: {0}\ [{1}, {2}]", path, publicKeyFileName, privateKeyFileName));
    }
    finally
    {
    rsa.PersistKeyInCsp = false;
    }
    }
    }

    /// <summary>
    /// 用给定路径的RSA公钥文件加密纯文本。
    /// </summary>
    /// <param name="plainText">要加密的文本</param>
    /// <param name="pathToPublicKey">用于加密的公钥路径.</param>
    /// <returns>表示加密数据的64位编码字符串.</returns>
    public string Encrypt(string plainText, string pathToPublicKey)
    {
    using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
    {
    try
    {
    //加载公钥
    var publicXmlKey = File.ReadAllText(pathToPublicKey);
    rsa.FromXmlString(publicXmlKey);

    var bytesToEncrypt = System.Text.Encoding.Unicode.GetBytes(plainText);

    var bytesEncrypted = rsa.Encrypt(bytesToEncrypt, false);

    return Convert.ToBase64String(bytesEncrypted);
    }
    finally
    {
    rsa.PersistKeyInCsp = false;
    }
    }
    }

    /// <summary>
    /// Decrypts encrypted text given a RSA private key file path.给定路径的RSA私钥文件解密 加密文本
    /// </summary>
    /// <param name="encryptedText">加密的密文</param>
    /// <param name="pathToPrivateKey">用于加密的私钥路径.</param>
    /// <returns>未加密数据的字符串</returns>
    public string Decrypt(string encryptedText, string pathToPrivateKey)
    {
    using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
    {
    try
    {
    var privateXmlKey = File.ReadAllText(pathToPrivateKey);
    rsa.FromXmlString(privateXmlKey);

    var bytesEncrypted = Convert.FromBase64String(encryptedText);

    var bytesPlainText = rsa.Decrypt(bytesEncrypted, false);

    return System.Text.Encoding.Unicode.GetString(bytesPlainText);
    }
    finally
    {
    rsa.PersistKeyInCsp = false;
    }
    }
    }
    }
    }
    四、SHA加密算法
            SHA,全称SecureHashAlgorithm,是一种数据加密算法,该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文,也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。

    C#代码:

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

    namespace PwdDemo
    {
    public class SHAHelper
    {
    public string SHAmd5Encrypt(string normalTxt)
    {
    var bytes = Encoding.Default.GetBytes(normalTxt);//求Byte[]数组
    var Md5 = new MD5CryptoServiceProvider();
    var encryptbytes = Md5.ComputeHash(bytes);//求哈希值
    return Base64To16(encryptbytes);//将Byte[]数组转为净荷明文(其实就是字符串)
    }

    public string SHA1Encrypt(string normalTxt)
    {
    var bytes = Encoding.Default.GetBytes(normalTxt);
    var SHA = new SHA1CryptoServiceProvider();
    var encryptbytes = SHA.ComputeHash(bytes);
    return Base64To16(encryptbytes);
    }
    public string SHA256Encrypt(string normalTxt)
    {
    var bytes = Encoding.Default.GetBytes(normalTxt);
    var SHA256 = new SHA256CryptoServiceProvider();
    var encryptbytes = SHA256.ComputeHash(bytes);
    return Base64To16(encryptbytes);
    }
    public string SHA384Encrypt(string normalTxt)
    {
    var bytes = Encoding.Default.GetBytes(normalTxt);
    var SHA384 = new SHA384CryptoServiceProvider();
    var encryptbytes = SHA384.ComputeHash(bytes);
    return Base64To16(encryptbytes);
    }
    public string SHA512Encrypt(string normalTxt)
    {
    var bytes = Encoding.Default.GetBytes(normalTxt);
    var SHA512 = new SHA512CryptoServiceProvider();
    var encryptbytes = SHA512.ComputeHash(bytes);
    return Base64To16(encryptbytes);
    }


    private string Base64To16(byte[] buffer)
    {
    string md_str = string.Empty;
    for (int i = 0; i < buffer.Length; i++)
    {
    md_str += buffer[i].ToString("x2");
    }
    return md_str;
    }
    }
    }
    以上内容大部分摘自网络

  • 相关阅读:
    dp
    康拓展开
    MST + 树形 dp
    树上对抗搜索
    求树上任意一点所能到达的最远距离
    将一棵树变成一个环
    树形dp
    区间dp
    区间dp
    day07作业
  • 原文地址:https://www.cnblogs.com/earthtosky/p/10375604.html
Copyright © 2011-2022 走看看