diff --git a/SM4-with-AESENCLAST.md b/SM4-with-AESENCLAST.md index f0fcf39..6dd0bab 100644 --- a/SM4-with-AESENCLAST.md +++ b/SM4-with-AESENCLAST.md @@ -229,7 +229,28 @@ func gen_matrix(lookup [256]byte) (m [8]byte) { return } ``` +Similar python code: +``` +from pyfinite import genericmatrix + +def XOR(x, y): return x ^ y +def AND(x, y): return x & y +def DIV(x, y): return x + + +def matrix_from_cols(cols): + m = genericmatrix.GenericMatrix(size=(8, 8), zeroElement=0, identityElement=1, add=XOR, mul=AND, sub=XOR, div=DIV) + for i in range (8): + k = 7 - i + j = 1 << k + m.SetRow(i, [(cols[0] & j) >> k, (cols[1] & j) >> k, (cols[2] & j) >> k, (cols[3] & j) >> k, (cols[4] & j) >> k, (cols[5] & j) >> k, (cols[6] & j) >> k, (cols[7] & j) >> k]) + return m + + +def gen_matrix_based_table(table): + return matrix_from_cols([table[0x80] ^ table[0], table[0x40] ^ table[0], table[0x20] ^ table[0], table[0x10] ^ table[0], table[0x08] ^ table[0], table[0x04] ^ table[0], table[0x02] ^ table[0], table[0x01] ^ table[0]]) +``` # Reference * [AES-NI used in SM4](https://github.com/mjosaarinen/sm4ni) * [Advanced Encryption Standard (AES)](https://www.nist.gov/publications/advanced-encryption-standard-aes)