AES

 

AES 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法

Rijndael(读作rain-dahl)是由美国国家标准与技术协会(NIST)所选的高级加密标准(AES)的候选算法。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。

Rijndael 算法首先是一个密钥分组加密的算法,通过置换(permutations )和替换(substitutions)迭代加密,进过多轮操作形成密文。

AES算是Rijndael算法的一种特殊实现,选的分组为128bit(16字节),密钥可以使用128、192 和 256bit三种,而Rijndael使用的密钥和区块长度可以是32位的整数倍,以128位为下限,256比特为上限。加密过程中使用的密钥是由Rijndael密钥生成方案产生。

AES加密过程是在一个4×4的字节矩阵上运作,这个矩阵又称为“状态(state)”,其初值就是一个明文区块(矩阵中一个元素大小就是明文区块中的一个Byte)。(Rijndael加密法因支持更大的区块,其矩阵行数可视情况增加)加密时,各轮AES加密循环(除最后一轮外)均包含4个步骤:
AddRoundKey — 矩阵中的每一个字节都与该次轮秘钥(round key)做XOR运算;每个子密钥由密钥生成方案产生。
SubBytes — 通过非线性的替换函数,用查找表的方式把每个字节替换成对应的字节。
ShiftRows — 将矩阵中的每个横列进行循环式移位。
MixColumns — 为了充分混合矩阵中各个直行的操作。这个步骤使用线性转换来混合每列的四个字节。

RijndaelManager代码实现

  1.  
    using System;
  2.  
    using System.Collections.Generic;
  3.  
    using System.Text;
  4.  
    using System.Security.Cryptography;
  5.  
    using System.IO;
  6.  
     
  7.  
    namespace Csharp
  8.  
    {
  9.  
    class AESHelper
  10.  
    {
  11.  
    /// <summary>
  12.  
    /// AES加密
  13.  
    /// </summary>
  14.  
    /// <param name="Data">被加密的明文</param>
  15.  
    /// <param name="Key">密钥</param>
  16.  
    /// <param name="Vector">向量</param>
  17.  
    /// <returns>密文</returns>
  18.  
    public static String AESEncrypt(String Data, String Key, String Vector)
  19.  
    {
  20.  
    Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
  21.  
     
  22.  
    Byte[] bKey = new Byte[32];
  23.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  24.  
    Byte[] bVector = new Byte[16];
  25.  
    Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
  26.  
     
  27.  
    Byte[] Cryptograph = null; // 加密后的密文
  28.  
     
  29.  
    Rijndael Aes = Rijndael.Create();
  30.  
    try
  31.  
    {
  32.  
    // 开辟一块内存流
  33.  
    using (MemoryStream Memory = new MemoryStream())
  34.  
    {
  35.  
    // 把内存流对象包装成加密流对象
  36.  
    using (CryptoStream Encryptor = new CryptoStream(Memory,
  37.  
    Aes.CreateEncryptor(bKey, bVector),
  38.  
    CryptoStreamMode.Write))
  39.  
    {
  40.  
    // 明文数据写入加密流
  41.  
    Encryptor.Write(plainBytes, 0, plainBytes.Length);
  42.  
    Encryptor.FlushFinalBlock();
  43.  
     
  44.  
    Cryptograph = Memory.ToArray();
  45.  
    }
  46.  
    }
  47.  
    }
  48.  
    catch
  49.  
    {
  50.  
    Cryptograph = null;
  51.  
    }
  52.  
     
  53.  
    return Convert.ToBase64String(Cryptograph);
  54.  
    }
  55.  
     
  56.  
    /// <summary>
  57.  
    /// AES解密
  58.  
    /// </summary>
  59.  
    /// <param name="Data">被解密的密文</param>
  60.  
    /// <param name="Key">密钥</param>
  61.  
    /// <param name="Vector">向量</param>
  62.  
    /// <returns>明文</returns>
  63.  
    public static String AESDecrypt(String Data, String Key, String Vector)
  64.  
    {
  65.  
    Byte[] encryptedBytes = Convert.FromBase64String(Data);
  66.  
    Byte[] bKey = new Byte[32];
  67.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  68.  
    Byte[] bVector = new Byte[16];
  69.  
    Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
  70.  
     
  71.  
    Byte[] original = null; // 解密后的明文
  72.  
     
  73.  
    Rijndael Aes = Rijndael.Create();
  74.  
    try
  75.  
    {
  76.  
    // 开辟一块内存流,存储密文
  77.  
    using (MemoryStream Memory = new MemoryStream(encryptedBytes))
  78.  
    {
  79.  
    // 把内存流对象包装成加密流对象
  80.  
    using (CryptoStream Decryptor = new CryptoStream(Memory,
  81.  
    Aes.CreateDecryptor(bKey, bVector),
  82.  
    CryptoStreamMode.Read))
  83.  
    {
  84.  
    // 明文存储区
  85.  
    using (MemoryStream originalMemory = new MemoryStream())
  86.  
    {
  87.  
    Byte[] Buffer = new Byte[1024];
  88.  
    Int32 readBytes = 0;
  89.  
    while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
  90.  
    {
  91.  
    originalMemory.Write(Buffer, 0, readBytes);
  92.  
    }
  93.  
     
  94.  
    original = originalMemory.ToArray();
  95.  
    }
  96.  
    }
  97.  
    }
  98.  
    }
  99.  
    catch
  100.  
    {
  101.  
    original = null;
  102.  
    }
  103.  
    return Encoding.UTF8.GetString(original);
  104.  
    }
  105.  
     
  106.  
     
  107.  
     
  108.  
    /// <summary>
  109.  
    /// AES加密(无向量)
  110.  
    /// </summary>
  111.  
    /// <param name="plainBytes">被加密的明文</param>
  112.  
    /// <param name="key">密钥</param>
  113.  
    /// <returns>密文</returns>
  114.  
    public static string AESEncrypt(String Data, String Key)
  115.  
    {
  116.  
    MemoryStream mStream = new MemoryStream();
  117.  
    RijndaelManaged aes = new RijndaelManaged();
  118.  
     
  119.  
    byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
  120.  
    Byte[] bKey = new Byte[32];
  121.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  122.  
     
  123.  
    aes.Mode = CipherMode.ECB;
  124.  
    aes.Padding = PaddingMode.PKCS7;
  125.  
    aes.KeySize = 128;
  126.  
    //aes.Key = _key;
  127.  
    aes.Key = bKey;
  128.  
    //aes.IV = _iV;
  129.  
    CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
  130.  
    try
  131.  
    {
  132.  
    cryptoStream.Write(plainBytes, 0, plainBytes.Length);
  133.  
    cryptoStream.FlushFinalBlock();
  134.  
    return Convert.ToBase64String(mStream.ToArray());
  135.  
    }
  136.  
    finally
  137.  
    {
  138.  
    cryptoStream.Close();
  139.  
    mStream.Close();
  140.  
    aes.Clear();
  141.  
    }
  142.  
    }
  143.  
     
  144.  
     
  145.  
    /// <summary>
  146.  
    /// AES解密(无向量)
  147.  
    /// </summary>
  148.  
    /// <param name="encryptedBytes">被加密的明文</param>
  149.  
    /// <param name="key">密钥</param>
  150.  
    /// <returns>明文</returns>
  151.  
    public static string AESDecrypt(String Data, String Key)
  152.  
    {
  153.  
    Byte[] encryptedBytes = Convert.FromBase64String(Data);
  154.  
    Byte[] bKey = new Byte[32];
  155.  
    Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
  156.  
     
  157.  
    MemoryStream mStream = new MemoryStream(encryptedBytes);
  158.  
    //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
  159.  
    //mStream.Seek( 0, SeekOrigin.Begin );
  160.  
    RijndaelManaged aes = new RijndaelManaged();
  161.  
    aes.Mode = CipherMode.ECB;
  162.  
    aes.Padding = PaddingMode.PKCS7;
  163.  
    aes.KeySize = 128;
  164.  
    aes.Key = bKey;
  165.  
    //aes.IV = _iV;
  166.  
    CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
  167.  
    try
  168.  
    {
  169.  
    byte[] tmp = new byte[encryptedBytes.Length + 32];
  170.  
    int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
  171.  
    byte[] ret = new byte[len];
  172.  
    Array.Copy(tmp, 0, ret, 0, len);
  173.  
    return Encoding.UTF8.GetString(ret);
  174.  
    }
  175.  
    finally
  176.  
    {
  177.  
    cryptoStream.Close();
  178.  
    mStream.Close();
  179.  
    aes.Clear();
  180.  
    }
  181.  
    }
  182.  
    }
  183.  
    }

AesManager代码实现

  1.  
    using System;
  2.  
    using System.IO;
  3.  
    using System.Security.Cryptography;
  4.  
     
  5.  
    namespace Aes_Example
  6.  
    {
  7.  
    class AesExample
  8.  
    {
  9.  
    public static void Main()
  10.  
    {
  11.  
    try
  12.  
    {
  13.  
    string original = "Here is some data to encrypt!";
  14.  
     
  15.  
    // Create a new instance of the AesManaged
  16.  
    // class. This generates a new key and initialization
  17.  
    // vector (IV).
  18.  
    using (AesManaged myAes = new AesManaged())
  19.  
    {
  20.  
    // Encrypt the string to an array of bytes.
  21.  
    byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
  22.  
     
  23.  
    // Decrypt the bytes to a string.
  24.  
    string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
  25.  
     
  26.  
    //Display the original data and the decrypted data.
  27.  
    Console.WriteLine("Original: {0}", original);
  28.  
    Console.WriteLine("Round Trip: {0}", roundtrip);
  29.  
    }
  30.  
     
  31.  
    }
  32.  
    catch (Exception e)
  33.  
    {
  34.  
    Console.WriteLine("Error: {0}", e.Message);
  35.  
    }
  36.  
    }
  37.  
    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
  38.  
    {
  39.  
    // Check arguments.
  40.  
    if (plainText == null || plainText.Length <= 0)
  41.  
    throw new ArgumentNullException("plainText");
  42.  
    if (Key == null || Key.Length <= 0)
  43.  
    throw new ArgumentNullException("Key");
  44.  
    if (IV == null || IV.Length <= 0)
  45.  
    throw new ArgumentNullException("IV");
  46.  
    byte[] encrypted;
  47.  
    // Create an AesManaged object
  48.  
    // with the specified key and IV.
  49.  
    using (AesManaged aesAlg = new AesManaged())
  50.  
    {
  51.  
    aesAlg.Key = Key;
  52.  
    aesAlg.IV = IV;
  53.  
     
  54.  
    // Create a decrytor to perform the stream transform.
  55.  
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
  56.  
     
  57.  
    // Create the streams used for encryption.
  58.  
    using (MemoryStream msEncrypt = new MemoryStream())
  59.  
    {
  60.  
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  61.  
    {
  62.  
    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
  63.  
    {
  64.  
     
  65.  
    //Write all data to the stream.
  66.  
    swEncrypt.Write(plainText);
  67.  
    }
  68.  
    encrypted = msEncrypt.ToArray();
  69.  
    }
  70.  
    }
  71.  
    }
  72.  
     
  73.  
     
  74.  
    // Return the encrypted bytes from the memory stream.
  75.  
    return encrypted;
  76.  
     
  77.  
    }
  78.  
     
  79.  
    static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
  80.  
    {
  81.  
    // Check arguments.
  82.  
    if (cipherText == null || cipherText.Length <= 0)
  83.  
    throw new ArgumentNullException("cipherText");
  84.  
    if (Key == null || Key.Length <= 0)
  85.  
    throw new ArgumentNullException("Key");
  86.  
    if (IV == null || IV.Length <= 0)
  87.  
    throw new ArgumentNullException("IV");
  88.  
     
  89.  
    // Declare the string used to hold
  90.  
    // the decrypted text.
  91.  
    string plaintext = null;
  92.  
     
  93.  
    // Create an AesManaged object
  94.  
    // with the specified key and IV.
  95.  
    using (AesManaged aesAlg = new AesManaged())
  96.  
    {
  97.  
    aesAlg.Key = Key;
  98.  
    aesAlg.IV = IV;
  99.  
     
  100.  
    // Create a decrytor to perform the stream transform.
  101.  
    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
  102.  
     
  103.  
    // Create the streams used for decryption.
  104.  
    using (MemoryStream msDecrypt = new MemoryStream(cipherText))
  105.  
    {
  106.  
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
  107.  
    {
  108.  
    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
  109.  
    {
  110.  
     
  111.  
    // Read the decrypted bytes from the decrypting stream
  112.  
    // and place them in a string.
  113.  
    plaintext = srDecrypt.ReadToEnd();
  114.  
    }
  115.  
    }
  116.  
    }
  117.  
     
  118.  
    }
  119.  
     
  120.  
    return plaintext;
  121.  
    }
  122.  
    }
  123.  
    }

C#实现AES加密解密的更多相关文章

  1. 非对称技术栈实现AES加密解密

    非对称技术栈实现AES加密解密 正如前面的一篇文章所述,https协议的SSL层是实现在传输层之上,应用层之下,也就是说在应用层上看到的请求还是明码的,对于某些场景下要求这些http请求参数是非可读的 ...

  2. C#中使用DES和AES加密解密

    C#中使用DES和AES加密解密 2008-01-12 09:37 using System;using System.Text;using System.Security.Cryptography; ...

  3. C#, Java, PHP, Python和Javascript几种语言的AES加密解密实现[转载]

    原文:http://outofmemory.cn/code-snippet/35524/AES-with-javascript-java-csharp-python-or-php c#里面的AES加密 ...

  4. ruby AES加密解密

    最近和京东合作做一个项目,在接口对接传递参数时,参数需要通过AES加密解密. 本来想到用gem 'aescrypt'处理,但是aescrypt的编码方式用的base64,而京东那边用的是16进制.所以 ...

  5. openssl与cryptoAPI交互AES加密解密

    继上次只有CryptoAPI的加密后,这次要实现openssl的了 动机:利用CryptoAPI制作windows的IE,火狐和chrome加密控件后,这次得加上与android的加密信息交互 先前有 ...

  6. java使用AES加密解密 AES-128-ECB加密

    java使用AES加密解密 AES-128-ECB加密 import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; impo ...

  7. AES加密解密——AES在JavaWeb项目中前台JS加密,后台Java解密的使用

    一:前言 在软件开发中,经常要对数据进行传输,数据在传输的过程中可能被拦截,被监听,所以在传输数据的时候使用数据的原始内容进行传输的话,安全隐患是非常大的.因此就要对需要传输的数据进行在客户端进行加密 ...

  8. AES加密解密 助手类 CBC加密模式

    "; string result1 = AESHelper.AesEncrypt(str); string result2 = AESHelper.AesDecrypt(result1); ...

  9. php与java通用AES加密解密算法

    AES指高级加密标准(Advanced Encryption Standard),是当前最流行的一种密码算法,在web应用开发,特别是对外提供接口时经常会用到,下面是我整理的一套php与java通用的 ...

  10. Java 关于密码处理的工具类[MD5编码][AES加密/解密]

    项目中又遇到了加密问题,又去翻了半天,然后做测试,干脆就把常用的两类小结一下. 1.第一种所谓的MD5加密 其实也不算加密,只是基于Hash算法的不可逆编码而已,等于说,一旦经过MD5处理,是不可能从 ...

随机推荐

  1. 推荐 11 个好用的 JS 动画库

    为了保证的可读性,本文采用意译而非直译. 1.Three.js 超过46K的星星,这个流行的库提供了非常多的3D显示功能,以一种直观的方式使用 WebGL.这个库提供了<canvas>. ...

  2. GlusterFS 安装

    一.简介 GlusterFS 是近年兴起的一个高性能开源分布式文件系统,其目标是全局命名空间.分布式前端的高性能文件系统,目前已被 RedHat 看中,GlusterFS 具有高扩展.高可性.高性能. ...

  3. jquery实现select数据回显

    [html] view plain copy     <select class="div_select_re" id="edit_technicalGrade&q ...

  4. 范仁义html+css课程---9、video、audio、canvas和svg元素略讲

    范仁义html+css课程---9.video.audio.canvas和svg元素略讲 一.总结 一句话总结: video:HTML5视频标签. audio:html5音频标签. canvas:绘制 ...

  5. AES采用CBC模式128bit加密工具类

    写在前面 安全测试ECB模式过于简单需要改为CBC模式加密以下为工具类及测试 AESUtils.java package com.sgcc.mobile.utils; import sun.misc. ...

  6. Quartus Prime 与 Modelsim 调试 及do文件使用

    Quartus Prime 与 Modelsim 调试 及do文件使用 2019-06-28 11:12:50 RushBTaotao 阅读数 49更多 分类专栏: IntelFPGA-Softwar ...

  7. npm和yarn常用调试命令

    yarn查看全局安装路径 yarn global dir npm查看所有全局安装的包<全局路径也会显示> npm list --depth=0 -global

  8. oracle plsql 自定义异常

    set serveroutput on DECLARE ; pename emp.ename%type; --自定义异常 no_emp_found exception; begin open cemp ...

  9. LwIP应用开发笔记之三:LwIP无操作系统UDP客户端

    前一节我们实现了基于RAW API的UDP服务器,在接下来,我们进一步利用RAW API实现UDP客户端. 1.UDP协议简述 UDP协议全称是用户数据报协议,在网络中它与TCP协议一样用于处理数据包 ...

  10. Python线程池及其原理和使用(超级详细)

    系统启动一个新线程的成本是比较高的,因为它涉及与操作系统的交互.在这种情形下,使用线程池可以很好地提升性能,尤其是当程序中需要创建大量生存期很短暂的线程时,更应该考虑使用线程池. 线程池在系统启动时即 ...