Aes加密/解密示例项目
#AesEncrypt:Aes加密/解密示例项目 <br>
附件中的“AesEncrypt.zip”是本项目的exe文件,可直接下载下来运行和查看。
*高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。*<br>
好的百科已普及,现在来看看这Aes怎么使用,由于需要把加密后的byte[]输出成字符串,但是普通字符串无法兼容,所以这里使用的base64字符串。详见代码AesEncrypt\AesEncrypt.cs。<br>
为了直观的看到Aes的加解密过程,现在给出几个示例,如下图<br>
1.在“未加密”的文本框中输入一个普通的字符串,点击“加密”按钮,将在”已加密“的文本框中得到一个Aes加密后的base64字符串。**这个“已加密”的base64字符串就可以放到系统中使用了,例如可以填到数据库链接字符串,也可以存储得到数据中。**<br>
2.第一步完成后,“已加密”文本框中已经被填写了Aes加密后的base64字符串,为了看到效果,可以把“未加密”文本框中的普通文本删掉,然后点击“解密”按钮,就可以在“未加密”文本框中看到之前的普通文本。<br>
3.经过以上两步操作,我想这个窗体已经完成了示例的作用,Aes加密需要两个byte[],一个是IV,它是对称算法的初始化向量,一个是Key,它是对称算法的密钥。IV是一个Length=16的byte[],Key是一个Length=32的byte[],**因此可以在AesEncrypt\AesEncrypt.cs类中设置自己的固定密钥用以在程序中加密/解密,如以下代码中所示,可以填写任意的数字,来当做密钥。**<br>
```C#
/// <summary>
/// 对称算法的密钥
/// </summary>
private readonly static byte[] aesKey = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 };
/// <summary>
/// 对称算法的初始化向量
/// </summary>
private readonly static byte[] aesIV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
```

以上步骤是在程序中的基本使用方式,Aes还可以有更多的用途,以下来个抛砖引玉。<br>
1.在“玩玩解密”窗体中点击“发送”按钮之后,将把“未加密”中的文本使用Aes加密后转换成base64字符串填写到“已加密”文本框中,同时将利用以下代码将Aes类可随机生成的IV和Key(注意IV和Key都是byte[]),转换为base64后分别填写到“向量(IV)”和“密钥(Key)”中。<br>
```C#
private void button1_Click(object sender, EventArgs e)
{
using (Aes myAes = Aes.Create())
{
AesEncryptExtension aes = new AesEncryptExtension();
textBox2.Text = aes.Encrypt(textBox1.Text, myAes.Key, myAes.IV);
textBox3.Text = Convert.ToBase64String(myAes.IV);
textBox4.Text = Convert.ToBase64String(myAes.Key);
}
Form3 form = new Form3();
form.Show();
}
```

2.第一步完成后,同时会弹出“接收密文”窗体,如下图。将“玩玩解密”窗体中的“已加密”、“向量(IV)”和“密钥(key)”填写到“接收密文”窗体对应文本框中,将获取到未加密的普通文本。<br>
3.以上所示,是手动填写密文、IV和key来获取内容。当然你也可以自动传过去,只要两个系统的iv和key相同就可以实现解密,前提是两个系统中的动态密钥规律要相同,说到这里我想聪明的你应该已经知道Aes加密怎么玩了,好好想想,可以有多种应用。<br>
举个例子,图例解释,IV和key合称为钥匙,IV和Key生成算法称为钥匙机,每一把被生产出来的钥匙都刻着钥匙编号,Aes本身称为保险柜,被加密内容则会被放进“保险柜”。两方同时使用钥匙机生产钥匙,每一把钥匙都刻着钥匙编号,运输的时候只运输保险柜和钥匙编号,接收到保险柜的一方,用钥匙编号从钥匙机中拿钥匙打开保险柜,取得加密内容。以上例可称为一个较为简单的Aes应用方式。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace AesEncrypt
{
/// <summary>
/// Aes加密算法适用于固定的加解密
/// </summary>
public static class AesEncrypt
{
/// <summary>
/// 对称算法的密钥
/// </summary>
private readonly static byte[] aesKey = { , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , };
/// <summary>
/// 对称算法的初始化向量
/// </summary>
private readonly static byte[] aesIV = { , , , , , , , , , , , , , , , }; /// <summary>
/// 加密
/// </summary>
/// <param name="Text">被加密的字符串</param>
/// <returns>Base64</returns>
public static string Encrypt(string Text)
{
byte[] encrypted;
encrypted = EncryptStringToBytes_Aes(Text, aesKey, aesIV);
return Convert.ToBase64String(encrypted);
} private static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= )
{
throw new ArgumentNullException("plainText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
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;
} /// <summary>
/// 解密
/// </summary>
/// <param name="text">被Aes加密后的Base64</param>
/// <returns>字符串</returns>
public static string Decrypt(string text)
{
string roundtrip; byte[] myByte = Convert.FromBase64String(text);
roundtrip = DecryptStringFromBytes_Aes(myByte, aesKey, aesIV); return roundtrip;
}
private static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= )
{
throw new ArgumentNullException("cipherText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
// Declare the string used to hold
// the decrypted text.
string plaintext; // Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
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;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace AesEncrypt
{
/// <summary>
/// Aes扩展方法
/// </summary>
public class AesEncryptExtension
{ /// <summary>
/// 加密
/// </summary>
/// <param name="Text">被加密的字符串</param>
/// <param name="aesKey">对称算法的密钥</param>
/// <param name="aesIV">设置对称算法的初始化向量</param>
/// <returns>Base64</returns>
public string Encrypt(string Text, byte[] aesKey, byte[] aesIV)
{
byte[] encrypted;
encrypted = EncryptStringToBytes_Aes(Text, aesKey, aesIV);
return Convert.ToBase64String(encrypted);
} private byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= )
{
throw new ArgumentNullException("plainText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
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;
} /// <summary>
/// 解密
/// </summary>
/// <param name="text">被Aes加密后的Base64</param>
/// <param name="aesKey">对称算法的密钥</param>
/// <param name="aesIV">设置对称算法的初始化向量</param>
/// <returns>字符串</returns>
public string Decrypt(string text, byte[] aesKey, byte[] aesIV)
{
string roundtrip; byte[] myByte = Convert.FromBase64String(text);
roundtrip = DecryptStringFromBytes_Aes(myByte, aesKey, aesIV); return roundtrip;
}
private string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= )
{
throw new ArgumentNullException("cipherText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
// Declare the string used to hold
// the decrypted text.
string plaintext; // Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
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;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace AesEncrypt
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{ textBox2.Text = AesEncrypt.Encrypt(textBox1.Text);
} private void button2_Click(object sender, EventArgs e)
{ textBox1.Text = AesEncrypt.Decrypt(textBox2.Text);
} private void 玩玩解密ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Show();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace AesEncrypt
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
using (Aes myAes = Aes.Create())
{
AesEncryptExtension aes = new AesEncryptExtension();
textBox2.Text = aes.Encrypt(textBox1.Text, myAes.Key, myAes.IV);
textBox3.Text = Convert.ToBase64String(myAes.IV);
textBox4.Text = Convert.ToBase64String(myAes.Key);
}
Form3 form = new Form3();
form.Show();
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace AesEncrypt
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
AesEncryptExtension aes = new AesEncryptExtension();
byte[] aesIV = Convert.FromBase64String(textBox3.Text);
byte[] aesKey = Convert.FromBase64String(textBox4.Text); textBox1.Text = aes.Decrypt(textBox2.Text, aesKey, aesIV);
}
}
}
Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法
Aes加密/解密示例项目的更多相关文章
- 你真的了解字典(Dictionary)吗? C# Memory Cache 踩坑记录 .net 泛型 结构化CSS设计思维 WinForm POST上传与后台接收 高效实用的.NET开源项目 .net 笔试面试总结(3) .net 笔试面试总结(2) 依赖注入 C# RSA 加密 C#与Java AES 加密解密
你真的了解字典(Dictionary)吗? 从一道亲身经历的面试题说起 半年前,我参加我现在所在公司的面试,面试官给了一道题,说有一个Y形的链表,知道起始节点,找出交叉节点.为了便于描述,我把上面 ...
- AES加密解密——AES在JavaWeb项目中前台JS加密,后台Java解密的使用
一:前言 在软件开发中,经常要对数据进行传输,数据在传输的过程中可能被拦截,被监听,所以在传输数据的时候使用数据的原始内容进行传输的话,安全隐患是非常大的.因此就要对需要传输的数据进行在客户端进行加密 ...
- 非对称技术栈实现AES加密解密
非对称技术栈实现AES加密解密 正如前面的一篇文章所述,https协议的SSL层是实现在传输层之上,应用层之下,也就是说在应用层上看到的请求还是明码的,对于某些场景下要求这些http请求参数是非可读的 ...
- ruby AES加密解密
最近和京东合作做一个项目,在接口对接传递参数时,参数需要通过AES加密解密. 本来想到用gem 'aescrypt'处理,但是aescrypt的编码方式用的base64,而京东那边用的是16进制.所以 ...
- Java 关于密码处理的工具类[MD5编码][AES加密/解密]
项目中又遇到了加密问题,又去翻了半天,然后做测试,干脆就把常用的两类小结一下. 1.第一种所谓的MD5加密 其实也不算加密,只是基于Hash算法的不可逆编码而已,等于说,一旦经过MD5处理,是不可能从 ...
- .Net Core AES加密解密
一.AES说明 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准用来替 ...
- C# 实现 JAVA AES加密解密[原创]
以下是网上普遍能收到的JAVA AES加密解密方法. 因为里面用到了KeyGenerator 和 SecureRandom,但是.NET 里面没有这2个类.无法使用安全随机数生成KEY. 我们在接收J ...
- crypto AES 加密 解密
1.aes加密解密说明 https://juejin.im/entry/59eea48e6fb9a0451968c25f aes是对称加密算法 md5是摘要算法,不算是加密,主要用来对信息一致性和完整 ...
- C#中使用DES和AES加密解密
C#中使用DES和AES加密解密 2008-01-12 09:37 using System;using System.Text;using System.Security.Cryptography; ...
随机推荐
- 给定一个矩阵 A, 返回 A 的转置矩阵。
给定一个矩阵 A, 返回 A 的转置矩阵. 矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引. 示例 1: 输入:[[1,2,3],[4,5,6],[7,8,9]]输出:[[1,4,7], ...
- 水果商城 ( Iview+ SSM + MySQL )
因为时间原因,只做了后台,前台本来是打算使用 uni 框架 的. 有文档.E-R流程图.数据库文件. 项目源码地址:https://github.com/oukele/MyProject-Two
- php类知识---最疯狂的魔术方法serialize,_sleep,__wakeup,unserialize,__autoload,__clone
serialize-----把实例化的对象写入文件 __sleep 调用serialize时触发 <?php class mycoach { public function __construc ...
- vue3.0以上关于打包后出现空白页和路由不起作用
1.解决页面空白,找不到资源 在项目根目录中的vue.config.js中publicPath: '/'修改为publicPath: './',如果没有这个文件,新建一个,基础代码为: module. ...
- ibatis和mybatis中的BatchExecutor
ibatis中的的处理方法 spring集成了ibatis的批量提交的功能,我们只要调用API就可以了 首先在你的dao中需要继承org.springframework.orm.ibatis.supp ...
- EntityManager的merge()方法
EntityManager的merge()方法相当于hibernate中session的saveOrUpdate()方法: 用于实体的插入和更新操作:
- js拖拽文件夹上传
由于项目需要上传文件到服务器,于是便在文件上传的基础上增加了拖拽上传.拖拽上传当然属于文件上传的一部分,只不过在文件上传的基础上增加了拖拽的界面,主要在于前台的交互, 从拖拽的文件中获取文件列表然后调 ...
- Confluence 6.15 博客页面(Blog Posts)宏
博客页面宏允许你 Confluence 页面中显示博客页面.通过单击博客的标题将会把你链接到博客页面中. 使用博客页面宏 为了将博客页面宏添加到页面中: 从编辑工具栏中,选择 插入(Insert) ...
- getFieldDecorator用法(三)——Table增删改
后台管理系统常用到表单的增删改,这里也做了个封装 例如:user/index.js import React from 'react' import { Card, Button, Table, Fo ...
- Python 之类与对象及继承
类与对象 学习类的语法 关键字 class 类别,分类class 类名:属性特性特征类名的编写规范:首字母大写 驼峰命令 见名知意--->遵守规范.Math StudentInfoclass S ...