GF(2^8)乘法

最近在学AES,实现了一下伽罗瓦域(2^8)乘法。

至于什么是伽罗瓦域解释起来比较复杂,我也不一定能解释清楚,自行google。这里只是给出一个简单直观的实现。

#include<iostream>
#include<fstream>
using namespace std;
unsigned char GFmul(unsigned char a, unsigned char b){
    //GF(2^8) 乘法
    unsigned char result = 0;
    //若b为奇数,则先累积a
    if((b&1) == 1)result = a;
    b >>= 1;
    for(int i = 1; i < 8; i ++){
        //从b1开始遍历,若遇到bi为1,则累积a。a每次乘2自增
        if(a > 127){
            a = (a << 1) ^ 0x1b;
        }
        else{
            a <<= 1;
        }
        if((b&1) == 1){
            result ^= a;
        }
        b >>= 1;
    }
    return result;
}
int main(){
    //测试用例,输出所有数的乘法结果,看是否均匀
    int count[256];
    for(int i = 0; i < 256; i ++)count[i] = 0;
    unsigned char x, y;
    x = 0;
    do{
        y = 0;
        do{
            count[GFmul(x, y)] ++;
            y ++;
        }while(y != 0);
        x ++;
    }while(x != 0);
    ofstream write("Test.txt");
    for(int i = 0; i < 256; i ++)write<<i<<"\t"<<count[i]<<endl;
    write.close();
    return 0;
}
C++

 

posted @ 2013-10-22 21:36  7hat  阅读(1521)  评论(0编辑  收藏  举报