参考:https://en.wikipedia.org/wiki/Rijndael_S-box
#include <stdint.h> #define ROTL8(x,shift) ((uint8_t) ((x) << (shift)) | ((x) >> (8 - (shift)))) static void initialize_aes_sbox(uint8_t sbox[256]) { uint8_t p = 1, q = 1; /* loop invariant: p * q == 1 in the Galois field */ do { /* multiply p by 3 */ p = p ^ (p << 1) ^ (p & 0x80 ? 0x1B : 0); /* divide q by 3 (equals multiplication by 0xf6) */ q ^= q << 1; q ^= q << 2; q ^= q << 4; q ^= q & 0x80 ? 0x09 : 0; /* compute the affine transformation */ uint8_t xformed = q ^ ROTL8(q, 1) ^ ROTL8(q, 2) ^ ROTL8(q, 3) ^ ROTL8(q, 4); sbox[p] = xformed ^ 0x63; } while (p != 1); /* 0 is a special case since it has no inverse */ sbox[0] = 0x63; } static void initialize_aes_inv_sbox(uint8_t *inv_sbox) { uint8_t sbox[256]; int32_t i; initialize_aes_sbox(sbox); for (i = 0; i < 256; i++) inv_sbox[sbox[i]] = i; }
def ROTL8(x,shift) : return 0xff & ( ( (x) << (shift) ) | ( (x) >> (8 - (shift) ) ) )def initialize_aes_sbox() : sbox = [None] * 256 p = q = 1 firstTime = True # loop invariant: p * q == 1 in the Galois field while p != 1 or firstTime : # To simulate a do/while loop # multiply p by 3 p = p ^ (p << 1) ^ (0x1B if p & 0x80 else 0) p = p & 0xff # divide q by 3 q ^= q << 1 q ^= q << 2 q ^= q << 4 q ^= 0x09 if q & 0x80 else 0 q = q & 0xff # compute the affine transformation xformed = q ^ ROTL8(q, 1) ^ ROTL8(q, 2) ^ ROTL8(q, 3) ^ ROTL8(q, 4) sbox[p] = xformed ^ 0x63 firstTime = False # 0 is a special case since it has no inverse sbox[0] = 0x63 return sbox def initialize_aes_inv_sbox(): inv_sbox = [None] * 256 i = 1 sbox = initialize_aes_sbox() for i in range(0, 256): inv_sbox[sbox[i]] = i return inv_sbox
发表评论