C#实现AES加密解密
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代码实现
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Security.Cryptography;
- using System.IO;
- namespace Csharp
- {
- class AESHelper
- {
- /// <summary>
- /// AES加密
- /// </summary>
- /// <param name="Data">被加密的明文</param>
- /// <param name="Key">密钥</param>
- /// <param name="Vector">向量</param>
- /// <returns>密文</returns>
- public static String AESEncrypt(String Data, String Key, String Vector)
- {
- Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
- Byte[] bKey = new Byte[32];
- Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
- Byte[] bVector = new Byte[16];
- Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
- Byte[] Cryptograph = null; // 加密后的密文
- Rijndael Aes = Rijndael.Create();
- try
- {
- // 开辟一块内存流
- using (MemoryStream Memory = new MemoryStream())
- {
- // 把内存流对象包装成加密流对象
- using (CryptoStream Encryptor = new CryptoStream(Memory,
- Aes.CreateEncryptor(bKey, bVector),
- CryptoStreamMode.Write))
- {
- // 明文数据写入加密流
- Encryptor.Write(plainBytes, 0, plainBytes.Length);
- Encryptor.FlushFinalBlock();
- Cryptograph = Memory.ToArray();
- }
- }
- }
- catch
- {
- Cryptograph = null;
- }
- return Convert.ToBase64String(Cryptograph);
- }
- /// <summary>
- /// AES解密
- /// </summary>
- /// <param name="Data">被解密的密文</param>
- /// <param name="Key">密钥</param>
- /// <param name="Vector">向量</param>
- /// <returns>明文</returns>
- public static String AESDecrypt(String Data, String Key, String Vector)
- {
- Byte[] encryptedBytes = Convert.FromBase64String(Data);
- Byte[] bKey = new Byte[32];
- Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
- Byte[] bVector = new Byte[16];
- Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
- Byte[] original = null; // 解密后的明文
- Rijndael Aes = Rijndael.Create();
- try
- {
- // 开辟一块内存流,存储密文
- using (MemoryStream Memory = new MemoryStream(encryptedBytes))
- {
- // 把内存流对象包装成加密流对象
- using (CryptoStream Decryptor = new CryptoStream(Memory,
- Aes.CreateDecryptor(bKey, bVector),
- CryptoStreamMode.Read))
- {
- // 明文存储区
- using (MemoryStream originalMemory = new MemoryStream())
- {
- Byte[] Buffer = new Byte[1024];
- Int32 readBytes = 0;
- while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
- {
- originalMemory.Write(Buffer, 0, readBytes);
- }
- original = originalMemory.ToArray();
- }
- }
- }
- }
- catch
- {
- original = null;
- }
- return Encoding.UTF8.GetString(original);
- }
- /// <summary>
- /// AES加密(无向量)
- /// </summary>
- /// <param name="plainBytes">被加密的明文</param>
- /// <param name="key">密钥</param>
- /// <returns>密文</returns>
- public static string AESEncrypt(String Data, String Key)
- {
- MemoryStream mStream = new MemoryStream();
- RijndaelManaged aes = new RijndaelManaged();
- byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
- Byte[] bKey = new Byte[32];
- Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
- aes.Mode = CipherMode.ECB;
- aes.Padding = PaddingMode.PKCS7;
- aes.KeySize = 128;
- //aes.Key = _key;
- aes.Key = bKey;
- //aes.IV = _iV;
- CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
- try
- {
- cryptoStream.Write(plainBytes, 0, plainBytes.Length);
- cryptoStream.FlushFinalBlock();
- return Convert.ToBase64String(mStream.ToArray());
- }
- finally
- {
- cryptoStream.Close();
- mStream.Close();
- aes.Clear();
- }
- }
- /// <summary>
- /// AES解密(无向量)
- /// </summary>
- /// <param name="encryptedBytes">被加密的明文</param>
- /// <param name="key">密钥</param>
- /// <returns>明文</returns>
- public static string AESDecrypt(String Data, String Key)
- {
- Byte[] encryptedBytes = Convert.FromBase64String(Data);
- Byte[] bKey = new Byte[32];
- Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
- MemoryStream mStream = new MemoryStream(encryptedBytes);
- //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );
- //mStream.Seek( 0, SeekOrigin.Begin );
- RijndaelManaged aes = new RijndaelManaged();
- aes.Mode = CipherMode.ECB;
- aes.Padding = PaddingMode.PKCS7;
- aes.KeySize = 128;
- aes.Key = bKey;
- //aes.IV = _iV;
- CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
- try
- {
- byte[] tmp = new byte[encryptedBytes.Length + 32];
- int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
- byte[] ret = new byte[len];
- Array.Copy(tmp, 0, ret, 0, len);
- return Encoding.UTF8.GetString(ret);
- }
- finally
- {
- cryptoStream.Close();
- mStream.Close();
- aes.Clear();
- }
- }
- }
- }
AesManager代码实现
- using System;
- using System.IO;
- using System.Security.Cryptography;
- namespace Aes_Example
- {
- class AesExample
- {
- public static void Main()
- {
- try
- {
- string original = "Here is some data to encrypt!";
- // Create a new instance of the AesManaged
- // class. This generates a new key and initialization
- // vector (IV).
- using (AesManaged myAes = new AesManaged())
- {
- // Encrypt the string to an array of bytes.
- byte[] encrypted = EncryptStringToBytes_Aes(original, myAes.Key, myAes.IV);
- // Decrypt the bytes to a string.
- string roundtrip = DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
- //Display the original data and the decrypted data.
- Console.WriteLine("Original: {0}", original);
- Console.WriteLine("Round Trip: {0}", roundtrip);
- }
- }
- catch (Exception e)
- {
- Console.WriteLine("Error: {0}", e.Message);
- }
- }
- static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
- {
- // Check arguments.
- if (plainText == null || plainText.Length <= 0)
- throw new ArgumentNullException("plainText");
- if (Key == null || Key.Length <= 0)
- throw new ArgumentNullException("Key");
- if (IV == null || IV.Length <= 0)
- throw new ArgumentNullException("IV");
- byte[] encrypted;
- // Create an AesManaged object
- // with the specified key and IV.
- using (AesManaged aesAlg = new AesManaged())
- {
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- // Create a decrytor to perform the stream transform.
- ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
- // Create the streams used for encryption.
- using (MemoryStream msEncrypt = new MemoryStream())
- {
- using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
- {
- using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
- {
- //Write all data to the stream.
- swEncrypt.Write(plainText);
- }
- encrypted = msEncrypt.ToArray();
- }
- }
- }
- // Return the encrypted bytes from the memory stream.
- return encrypted;
- }
- static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
- {
- // Check arguments.
- if (cipherText == null || cipherText.Length <= 0)
- throw new ArgumentNullException("cipherText");
- if (Key == null || Key.Length <= 0)
- throw new ArgumentNullException("Key");
- if (IV == null || IV.Length <= 0)
- throw new ArgumentNullException("IV");
- // Declare the string used to hold
- // the decrypted text.
- string plaintext = null;
- // Create an AesManaged object
- // with the specified key and IV.
- using (AesManaged aesAlg = new AesManaged())
- {
- aesAlg.Key = Key;
- aesAlg.IV = IV;
- // Create a decrytor to perform the stream transform.
- ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
- // Create the streams used for decryption.
- using (MemoryStream msDecrypt = new MemoryStream(cipherText))
- {
- using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
- {
- using (StreamReader srDecrypt = new StreamReader(csDecrypt))
- {
- // Read the decrypted bytes from the decrypting stream
- // and place them in a string.
- plaintext = srDecrypt.ReadToEnd();
- }
- }
- }
- }
- return plaintext;
- }
- }
- }
C#实现AES加密解密的更多相关文章
- 非对称技术栈实现AES加密解密
非对称技术栈实现AES加密解密 正如前面的一篇文章所述,https协议的SSL层是实现在传输层之上,应用层之下,也就是说在应用层上看到的请求还是明码的,对于某些场景下要求这些http请求参数是非可读的 ...
- C#中使用DES和AES加密解密
C#中使用DES和AES加密解密 2008-01-12 09:37 using System;using System.Text;using System.Security.Cryptography; ...
- C#, Java, PHP, Python和Javascript几种语言的AES加密解密实现[转载]
原文:http://outofmemory.cn/code-snippet/35524/AES-with-javascript-java-csharp-python-or-php c#里面的AES加密 ...
- ruby AES加密解密
最近和京东合作做一个项目,在接口对接传递参数时,参数需要通过AES加密解密. 本来想到用gem 'aescrypt'处理,但是aescrypt的编码方式用的base64,而京东那边用的是16进制.所以 ...
- openssl与cryptoAPI交互AES加密解密
继上次只有CryptoAPI的加密后,这次要实现openssl的了 动机:利用CryptoAPI制作windows的IE,火狐和chrome加密控件后,这次得加上与android的加密信息交互 先前有 ...
- java使用AES加密解密 AES-128-ECB加密
java使用AES加密解密 AES-128-ECB加密 import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; impo ...
- AES加密解密——AES在JavaWeb项目中前台JS加密,后台Java解密的使用
一:前言 在软件开发中,经常要对数据进行传输,数据在传输的过程中可能被拦截,被监听,所以在传输数据的时候使用数据的原始内容进行传输的话,安全隐患是非常大的.因此就要对需要传输的数据进行在客户端进行加密 ...
- AES加密解密 助手类 CBC加密模式
"; string result1 = AESHelper.AesEncrypt(str); string result2 = AESHelper.AesDecrypt(result1); ...
- php与java通用AES加密解密算法
AES指高级加密标准(Advanced Encryption Standard),是当前最流行的一种密码算法,在web应用开发,特别是对外提供接口时经常会用到,下面是我整理的一套php与java通用的 ...
- Java 关于密码处理的工具类[MD5编码][AES加密/解密]
项目中又遇到了加密问题,又去翻了半天,然后做测试,干脆就把常用的两类小结一下. 1.第一种所谓的MD5加密 其实也不算加密,只是基于Hash算法的不可逆编码而已,等于说,一旦经过MD5处理,是不可能从 ...
随机推荐
- R 语言输入输出 读取命令函参数
输入数据 使用键盘输入数据 只能处理小样本,很少使用 在创建 data.txt 字符串之后,用函数 read.table() 创建数据框 data.1.这种方法可以让我们把数据嵌入到R代码中,此处切记 ...
- OpenFOAM——圆柱绕流对流换热
本算例来自<ANSYS FLUENT技术基础与工程应用:流动传热与环境污染控制领域> TOP和DOWN为对称边界(symmetry),入口速度为0.01m/s,入口温度为300K,圆柱温度 ...
- save tracking results into csv file for oxuva long-term tracking dataset (from txt to csv)
save tracking results into csv file for oxuva long-term tracking dataset (from txt to csv) 2019-10-2 ...
- Java类成员初始化顺序
类中包含7中成员:1.静态变量 static2.final静态常量 final static3.静态代码块 static{} //多个代码块顺序执行 4.普通变量5.普通代码块 {} //多个代码 ...
- PL/SQL【32位】连接Oracle 11g【64位】
下载64位Oracle安装: 下载PL/SQL安装:下载instantclient-basic-win32-12.1.0.1.0.zip,解压后剪切instantclient_12_1文件夹,粘贴到O ...
- Linux 等待信号(sigsuspend)
/* sigsuspend()函数说明 */ #include <stdio.h> #include <signal.h> /* 知识补充: sigsuspend()函数 函数 ...
- Jackson的基本用法与拓展
目录 一.先搞两个测试需要使用的类 二.简单操作:obj与json互转 2.1.对象转json字符串 2.2.json字符串转对象 三.拓展需求 3.1.对象转json时,忽略某个字段 3.2.对象转 ...
- ERROR: CAN'T FIND PYTHON EXECUTABLE "PYTHON", YOU CAN SET THE PYTHON ENV VARIABLE.解决办法
错误原因:Node.js 在安装模块的时候报错,缺少python环境. 解决办法: 第一种方式: 安装Python及环境变量配置 一定要安装python2.7的版本 环境变量安装可以参考:http:/ ...
- spring boot使用AOP统一处理web请求
为了保证服务的高可用,及时发现问题,迅速解决问题,为应用添加log是必不可少的. 但是随着项目的增大,方法增多,每个方法加单独加日志处理会有很多冗余 那在SpringBoot项目中如何统一的处理Web ...
- spark 开启job history
1.首先需要创建spark.history.fs.logDirectory hadoop fs -mkdir hdfs://ns1:9000/user/hadoop/logs 2.修改hadoop-d ...