AES加密的过程:
https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
ECB模式:
分组加密,分组解密。
ISO10126:
这是填充方式的一种,旨将原文的长度边长组的大小的整数倍。
最后一个填充是填充的字节数,其它位随机数。
代码如下:
/*
* 参考资料:
* ISO10126:https://en.wikipedia.org/wiki/Padding_(cryptography)#ISO_10126
* AES 算法过程:
* https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
* http://blog.csdn.net/lisonglisonglisong/article/details/41909813
* ECB 模式实现思想:
* http://blog.csdn.net/sevenlater/article/details/50317999
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <string.h>
/*
* GF(2^8)的过程
*/
uint8_t gmult(uint8_t a, uint8_t b) {
uint8_t p = 0, i = 0, hbs = 0;
for (i = 0; i < 8; i++) {
if (b & 1) {
p ^= a;
}
hbs = a & 0x80;
a <<= 1;
if (hbs) a ^= 0x1b; // 0000 0001 0001 1011
b >>= 1;
}
return (uint8_t)p;
}
/*
* 四字节的加法
*/
void coef_add(uint8_t a[], uint8_t b[], uint8_t d[]) {
d[0] = a[0]^b[0];
d[1] = a[1]^b[1];
d[2] = a[2]^b[2];
d[3] = a[3]^b[3];
}
/*
* 四字节的乘法
*/
void coef_mult(uint8_t *a, uint8_t *b, uint8_t *d) {
d[0] = gmult(a[0],b[0])^gmult(a[3],b[1])^gmult(a[2],b[2])^gmult(a[1],b[3]);
d[1] = gmult(a[1],b[0])^gmult(a[0],b[1])^gmult(a[3],b[2])^gmult(a[2],b[3]);
d[2] = gmult(a[2],b[0])^gmult(a[1],b[1])^gmult(a[0],b[2])^gmult(a[3],b[3]);
d[3] = gmult(a[3],b[0])^gmult(a[2],b[1])^gmult(a[1],b[2])^gmult(a[0],b[3]);
}
/*
* AES-128 分组大小为4
*/
int Nb = 4;
/*
* AES-128 分组长度是4
*/
int Nk = 4;
/*
* AES-128 轮数是10
*/
int Nr = 10;
/*
* S-box 的表
*/
static uint8_t s_box[256] = {
// 0 1 2 3 4 5 6 7 8 9 a b c d e f
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, // 0
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, // 1
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, // 2
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, // 3
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, // 4
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, // 5
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, // 6
0x51, 0xa3, 0x40,