GF乘法
#include<iostream>
using namespace std;
unsigned char XTIME[8] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
int main(){
int a,b;
a=3;
b=6;
printf("%#X", mul(a,b));
}
int mul(int a,int b){
int i=0;
unsigned char tempmultiply = 0x00;
while(a!=0){
if(a%2==1)
tempmultiply ^= b * XTIME[i];
i++;
a>>=1;
}
return tempmultiply;
}
AES的S-Box生成
#include <cstdio>
unsigned char sbox[16][16];
void init();
unsigned char msb(unsigned short num);
unsigned char divide(unsigned short a,unsigned char b,unsigned char &r);
unsigned char multiply(unsigned char a,unsigned char b);
unsigned char inverse(unsigned char b);
unsigned char map(unsigned char a);
int main()
{
init();
unsigned char i, j;
for(i = 0; i <= 0xF; i++)
{
printf("\n");
for(j = 0; j <= 0xF; j++)
{
sbox[i][j] = map(sbox[i][j]);
printf("%02X ",sbox[i][j]);
}
}
return 0;
}
void init()
{
unsigned char i, j;
for(i = 0; i <= 0xF; i++)
{
for(j = 0; j <= 0xF; j++)
{
sbox[i][j] = inverse((i << 4) + j);
}
}
}
unsigned char msb(unsigned short num)
{
unsigned char i;
for(i = 0; i <= 8; i++)
{
if(!(num >> (i + 1)))
{
return i;
}
}
}
unsigned char divide(unsigned short a,unsigned char b,unsigned char &r)
{
unsigned char a_msb = msb(a);
unsigned char b_msb = msb(b);
if(a < b)
{
r = a;
return 0;
}
unsigned char bit = a_msb - b_msb;
unsigned short temp = b;
temp = temp << bit;
a = a ^ temp;
return (1 << bit) | divide(a, b, r);
}
unsigned char multiply(unsigned char a,unsigned char b)
{
unsigned char res = 0;
if(b & 0x01)
{
res = a;
}
for (unsigned char i = 1; i < 8; i++)
{
if(b & (0x01 << i))
{
unsigned char temp = a;
for(unsigned char j = 0; j < i; j++)
{
if(!(temp & 0x80))
{
temp <<= 1;
}
else
{
temp <<= 1;
temp = temp ^ 0x1B;
}
}
res = res ^ temp;
}
}
return res;
}
unsigned char inverse(unsigned char b)
{
if(b == 0)
return 0;
short r0 = 0x11B;
unsigned char r1 = b, r2, q;
unsigned char w0 = 0, w1 = 1, w2;
q = divide(r0, r1 , r2);
w2 = w0 ^ multiply(q, w1);
while(1)
{
if(r2 == 0)
break;
r0 = r1;
r1 = r2;
q = divide(r0, r1, r2);
w0 = w1;
w1 = w2;
w2 = w0 ^ multiply(q, w1);
}
return w1;
}
unsigned char map(unsigned char a)
{
unsigned char c = 0x63;
unsigned char res = 0x0;
unsigned char temp = 0x0;
unsigned char i;
for(i = 0; i < 8; i++)
{
temp = temp ^ ((a >> i) & 0x1) ^ ((a >> ((i + 4) % 8)) & 0x1);
temp = temp ^ ((a >> ((i + 5) % 8)) & 0x1) ^ ((a >> ((i + 6) % 8)) & 0x1);
temp = temp ^ ((a >> ((i + 7) % 8)) & 0x1) ^ ((c >> i) & 0x1);
res = res | (temp << i);
temp = 0x0;
}
return res;
}