code wiki / (root) / nx_aes_test.nx

nx_aes_test.nx source

↩ module page · 73 lines · 2325 B

1// nx_aes_test.nx -- known-answer test for AES-128 against the FIPS 2// 197 Appendix C.1 vector: 3// 4// Cipher Key: 000102030405060708090a0b0c0d0e0f 5// Plaintext: 00112233445566778899aabbccddeeff 6// Ciphertext: 69c4e0d86a7b0430d8cdb78070b4c55a 7// 8// expect_exit: 0 9// 10// license_tier: ORIGINAL 11 12import "nx_syscalls.nx" 13import "nx_aes.nx" 14 15func main() -> i64 { 16 let key: *u8 = sys_mmap(32) 17 let pt: *u8 = sys_mmap(32) 18 let ct: *u8 = sys_mmap(32) 19 let exp: *u8 = sys_mmap(32) 20 let sched: *u8 = sys_mmap(AES_EXP_LEN + 16) 21 22 // Key bytes 00 01 02 ... 0f 23 var i: i64 = 0 24 while i < 16 { key[i] = i & 0xff; i = i + 1 } 25 26 // Plaintext bytes 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff 27 pt[0] = 0x00; pt[1] = 0x11; pt[2] = 0x22; pt[3] = 0x33 28 pt[4] = 0x44; pt[5] = 0x55; pt[6] = 0x66; pt[7] = 0x77 29 pt[8] = 0x88; pt[9] = 0x99; pt[10] = 0xaa; pt[11] = 0xbb 30 pt[12] = 0xcc; pt[13] = 0xdd; pt[14] = 0xee; pt[15] = 0xff 31 32 // Expected ciphertext: 69 c4 e0 d8 6a 7b 04 30 d8 cd b7 80 70 b4 c5 5a 33 exp[0] = 0x69; exp[1] = 0xc4; exp[2] = 0xe0; exp[3] = 0xd8 34 exp[4] = 0x6a; exp[5] = 0x7b; exp[6] = 0x04; exp[7] = 0x30 35 exp[8] = 0xd8; exp[9] = 0xcd; exp[10] = 0xb7; exp[11] = 0x80 36 exp[12] = 0x70; exp[13] = 0xb4; exp[14] = 0xc5; exp[15] = 0x5a 37 38 aes128_expand_key(key, sched) 39 aes128_encrypt_block(pt, sched, ct) 40 41 // Compare 16 bytes; return 1+byte_index on mismatch. 42 var j: i64 = 0 43 while j < 16 { 44 let a: i64 = ct[j] as i64 45 let b: i64 = exp[j] as i64 46 if (a & 0xff) != (b & 0xff) { return 1 + j } 47 j = j + 1 48 } 49 50 // ---- Decrypt round-trip: decrypt(encrypt(pt)) must equal pt ----- 51 let rt: *u8 = sys_mmap(32) 52 aes128_decrypt_block(ct, sched, rt) 53 var k: i64 = 0 54 while k < 16 { 55 let a2: i64 = rt[k] as i64 56 let b2: i64 = pt[k] as i64 57 if (a2 & 0xff) != (b2 & 0xff) { return 32 + k } 58 k = k + 1 59 } 60 61 // ---- Decrypt the FIPS 197 Appendix C.1 ciphertext directly ------ 62 let dt: *u8 = sys_mmap(32) 63 aes128_decrypt_block(exp, sched, dt) 64 var m: i64 = 0 65 while m < 16 { 66 let a3: i64 = dt[m] as i64 67 let b3: i64 = pt[m] as i64 68 if (a3 & 0xff) != (b3 & 0xff) { return 64 + m } 69 m = m + 1 70 } 71 72 return 0 73}