I’m implementing the Advanced Encryption Standard (AES) in C. During the subBytes() step I’m having some problems on the conversion from char to binary.
With the code:
void subBytes(unsigned char* state) {
int i=0;
for(; i<=127; i++) {
printf("%d",getBitState(state, i));
if(i%32==0){printf("\n");}
else if(i%8==0) {printf(",");}
}
printf("\n");
}
int getBitState(unsigned char* state, int i) {
int bytePosition = i/8;
int bitPosition = i%8;
unsigned char byteValue = state[bytePosition];
return (byteValue >> (8-bitPosition)) & 1;
}
If the state matrix is:
50, 67, 246, 168,
136, 90, 48, 141,
49, 49, 152, 162,
224, 55, 7, 52,
The output is:
00110010,01000010,11110110,10101000
10001000,01011010,00110000,10001100
00110000,00110000,10011000,10100010
11100000,00110110,00000110,0011010
So, as you can see, some values are well converted from char to binary but others don’t. For example, the value 67 is converted in 01000010 (66).
The only pattern that I see is that odd numbers are converted in even binary numbers.
Can anybody spot what I’m doing wrong ?
Your getBitState function can be reduced to the following:
The double bang converts any nonzero value to 1.
Alternatively, since this is cryptography and speed is an issue, use a macro:
Here’s an ideone.