本文所使用的AES为官方提供的原型类
本文主要讲如何调用 并不涉及 具体原理
这里为调用
using System;
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 aesjm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string Cipher_8(string pwd, string mcode)//这里调用加密原型 加密字符最多只支持8字节
{
byte[] ping = Encoding.Unicode.GetBytes(pwd);
byte[] cipheredText = new byte[ping.Length];
byte[] keyBytes=Encoding.Unicode.GetBytes(mcode);
Aes a = new Aes(Aes.KeySize.Bits128, keyBytes);
a.Cipher(ping, cipheredText);
string d="";
foreach (var item in cipheredText)
{
d += item.ToString("x2");
}
return d;
}
public string DeCipher_8(string pwd, string mcode)//这里调用解密原型 用上边方法加密责用这个方法解密
{
byte[] cipheredText = new byte[16];
byte[] decipheredText = new byte[16];
byte[] keyBytes = Encoding.Unicode.GetBytes(mcode);
for (int i = 0; i < cipheredText.Length; i ++)
{
cipheredText[i] = (byte)Convert.ToInt32(pwd.Substring(i*2, 2),16);
}
Aes a = new Aes(Aes.KeySize.Bits128, keyBytes);
a.InvCipher(cipheredText, decipheredText);
return Encoding.Unicode.GetString(decipheredText);
}
public string Cipher_all(string pwd, string mcode)//这里进行了分组 处理可以实现任意长度字符的加密
{
int count = pwd.Length % 8;//获取余数
if (pwd.Length<8)
{
add(ref pwd, 8 - pwd.Length);//如果不到8位 责补空格
}
else
{
if (count!=0)
{
add(ref pwd, 8 - count);//如果大于8位 且有余数 那么补0 让他成为8的倍数
}
}
string result = "";
for (int i = 0; i < pwd.Length/8; i++)//把字符串分割为8位一组 8位一组 之后进行加密
{
result += Cipher_8(pwd.Substring(i * 8, 8), mcode); //分组加密之后再加到一起
}
return result;
}
public string DeCipher_all(string pwd, string mcode)//解密跟加密同理 不过解密不需要判断位数 因为是加密的都是8的倍数
{
int count = pwd.Length / 32;
string result="";
for (int i = 0; i < count; i++)
{ //因为每次的字符结尾可能是'\0'这样的话 就返回第一个了
result += DeCipher_8(pwd.Substring(i * 32, 32),mcode).TrimEnd(' ');//这里要注意 必须加.trimend 否则只会返回第一个
}
return result;
}
public void add(ref string a, int count) //这个函数用来补空格
{
for (int i = 0; i < count; i++)
{
a += " ";
}
}
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = Cipher_all(textBox1.Text, textBox2.Text);//按钮调用
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = DeCipher_all(textBox3.Text, textBox2.Text);//按钮调用
}
}
}
下面的为AES类原型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace aesjm
{
public class Aes // Advanced Encryption Standard
{
public enum KeySize { Bits128, Bits192, Bits256 }; // key size, in bits, for construtor
//byte16 24 32
private int Nb; // block size in 32-bit words. Always 4 for AES. (128 bits).
private int Nk; // key size in 32-bit words. 4, 6, 8. (128, 192, 256 bits).
private int Nr; // number of rounds. 10, 12, 14.
private byte[] key; // the seed key. size will be 4 * keySize from ctor.
private