# Validation of an AES implementation in Python 3

The Cryptographic Algorithm Validation Program (CAVP) defines validation testing for cryptographic algorithms approved by the US National Institute of Standards and Technology (NIST). All of the tests under CAVP, established by NIST and its Canadian counterpart (CSEC) in 1995, are handled by accredited third-party laboratories.

To assist prospective vendors in checking their implementations, NIST provides electronic versions of the vectors for the Known Answer Test (KAT) for the three NIST-approved symmetric cryptographic algorithms: AES, Triple-DES, and Skipjack. Also available are sample values for the Monte Carlo (MCT) test and the Multiblock Message (MMT) test for the same algorithms, thus completing the set of tests a cryptographic implementation (dubbed “Implementation Under Test”) will face during a formal validation. A detailed account of the procedures involved in validating AES implementations can be found in the NIST document The Advanced Encryption Standard Algorithm Validation Suite (AESAVS).

The NIST KAT validation suite for AES contains 72 files describing test vectors for different AES modes of operation: ECB (Electronic Codebook), CBC (Cipher Block Chaining), CFB (Cipher Feedback) and OFB (Output Feedback). Besides this partition, there are also separated tests for AES encryption and decryption, exemplified by the abridged contents of the file `ECBKeySbox128.rsp` (see below).

```# CAVS 11.1
# Config info for aes_values
# AESVS KeySbox test data for ECB
# State : Encrypt and Decrypt
# Key Length : 128
# Generated on Fri Apr 22 15:11:26 2011

[ENCRYPT]

COUNT = 0
KEY = 10a58869d74be5a374cf867cfb473859
PLAINTEXT = 00000000000000000000000000000000
CIPHERTEXT = 6d251e6944b051e04eaa6fb4dbf78465

COUNT = 1
KEY = caea65cdbb75e9169ecd22ebe6e54675
PLAINTEXT = 00000000000000000000000000000000
CIPHERTEXT = 6e29201190152df4ee058139def610bb

... (18 test cases omitted)

[DECRYPT]

COUNT = 0
KEY = 10a58869d74be5a374cf867cfb473859
CIPHERTEXT = 6d251e6944b051e04eaa6fb4dbf78465
PLAINTEXT = 00000000000000000000000000000000

COUNT = 1
KEY = caea65cdbb75e9169ecd22ebe6e54675
CIPHERTEXT = 6e29201190152df4ee058139def610bb
PLAINTEXT = 00000000000000000000000000000000

... (18 test cases omitted)
```

These vectors can be used to informally verify the correctness of an AES implementation, such as the one presented below, which successfully passed all 4,156 KAT tests involving ECB and CBC modes. This Python code differs from the one already presented in a previous blog only with respect to the input/output types accepted: if the input plaintext (ciphertext) is of integer type, so will be the correspondent ciphertext (plaintext) output. This feature simplifies validation testing, since the integer plaintexts and ciphertexts usually employed in those scenarios can be deal with directly without any type conversion.

```#!/usr/bin/python3
#
# Author: Joao H de A Franco (jhafranco@acm.org)
#
# Description: AES implementation in Python 3
#              (sundAES)
#
# Date: 2013-06-02 (version 1.1)
#       2012-01-16 (version 1.0)
#
# License: Attribution-NonCommercial-ShareAlike 3.0 Unported
#          (CC BY-NC-SA 3.0)
#===========================================================
import sys
from itertools import repeat
from functools import reduce
from copy import copy

__all__ = ["setKey","encrypt","decrypt"]

def memoize(func):
"""Memoization function"""
memo = {}
def helper(x):
if x not in memo:
memo[x] = func(x)
return memo[x]
return helper

def mult(p1,p2):
"""Multiply two polynomials in GF(2^8)/x^8+x^4+x^3+x+1"""
p = 0
while p2:
if p2&0x01:
p ^= p1
p1 <<= 1
if p1&0x100:
p1 ^= 0x1b
p2 >>= 1
return p&0xff

# Auxiliary one-parameter functions defined for memoization
# (to speed up multiplication in GF(2^8))

@memoize
def x2(y):
"""Multiplication by 2"""
return mult(2,y)

@memoize
def x3(y):
"""Multiplication by 3"""
return mult(3,y)

@memoize
def x9(y):
"""Multiplication by 9"""
return mult(9,y)

@memoize
def x11(y):
"""Multiplication by 11"""
return mult(11,y)

@memoize
def x13(y):
"""Multiplication by 13"""
return mult(13,y)

@memoize
def x14(y):
"""Multiplication by 14"""
return mult(14,y)

class AES:
"""Class definition for AES objects"""
keySizeTable = {"SIZE_128":16,
"SIZE_192":24,
"SIZE_256":32}
wordSizeTable = {"SIZE_128":44,
"SIZE_192":52,
"SIZE_256":60}
numberOfRoundsTable = {"SIZE_128":10,
"SIZE_192":12,
"SIZE_256":14}
cipherModeTable = {"MODE_ECB":1,
"MODE_CBC":2}
paddingTable = {"NoPadding":0,
"PKCS7Padding":1}
# S-Box
sBox = (0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,
0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,
0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,
0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,
0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,
0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,
0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,
0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,
0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,
0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,
0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,
0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,
0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,
0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,
0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,
0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,
0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16)
# Inverse S-Box
invSBox = (0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,
0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb,
0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,
0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,
0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,
0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e,
0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,
0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,
0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,
0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,
0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,
0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,
0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,
0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06,
0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,
0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b,
0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,
0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,
0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,
0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,
0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,
0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,
0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,
0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,
0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,
0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f,
0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,
0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,
0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,
0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,
0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,
0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d)

# Instance variables
wordSize = None
w = [None]*60 # Round subkeys list
keyDefined = None # Key definition flag
numberOfRounds = None
cipherMode = None
padding = None # Padding scheme
ivEncrypt = None # Initialization
ivDecrypt = None #  vectors

def __init__(self,mode,padding = "NoPadding"):
"""Create a new instance of an AES object"""
try:
assert mode in AES.cipherModeTable
except AssertionError:
print("Cipher mode not supported:",mode)
sys.exit("ValueError")
self.cipherMode = mode
try:
assert padding in AES.paddingTable
except AssertionError:
print("Padding scheme not supported:",padding)
sys.exit(ValueError)
self.padding = padding
self.keyDefined = False

def intToList(self,number):
"""Convert an 16-byte number into a 16-element list"""
return [(number>>i)&0xff for i in reversed(range(0,128,8))]

def intToList2(self,number):
"""Converts an integer into one (or more) 16-element list"""
lst = []
while number:
lst.append(number&0xff)
number >>= 8
m = len(lst)%16
if m == 0 and len(lst) != 0:
return lst[::-1]
else:
return list(bytes(16-m)) + lst[::-1]

def listToInt(self,lst):
"""Convert a list into a number"""
return reduce(lambda x,y:(x<<8)+y,lst)

def wordToState(self,wordList):
"""Convert list of 4 words into a 16-element state list"""
return [(wordList[i]>>j)&0xff
for j in reversed(range(0,32,8)) for i in range(4)]

def listToState(self,list):
"""Convert a 16-element list into a 16-element state list"""
return [list[i+j] for j in range(4) for i in range(0,16,4)]

stateToList = listToState # this function is an involution

def subBytes(self,state):
"""SubBytes transformation"""
return [AES.sBox[e] for e in state]

def invSubBytes(self,state):
"""Inverse SubBytes transformation"""
return [AES.invSBox[e] for e in state]

def shiftRows(self,s):
"""ShiftRows transformation"""
return s[:4]+s[5:8]+s[4:5]+s[10:12]+s[8:10]+s[15:]+s[12:15]

def invShiftRows(self,s):
"""Inverse ShiftRows transformation"""
return s[:4]+s[7:8]+s[4:7]+s[10:12]+s[8:10]+s[13:]+s[12:13]

def mixColumns(self,s):
"""MixColumns transformation"""
return [x2(s[i])^x3(s[i+4])^   s[i+8] ^   s[i+12]  for i in range(4)]+ \
[   s[i] ^x2(s[i+4])^x3(s[i+8])^   s[i+12]  for i in range(4)]+ \
[   s[i] ^   s[i+4] ^x2(s[i+8])^x3(s[i+12]) for i in range(4)]+ \
[x3(s[i])^   s[i+4] ^   s[i+8] ^x2(s[i+12]) for i in range(4)]

def invMixColumns(self,s):
"""Inverse MixColumns transformation"""
return [x14(s[i])^x11(s[i+4])^x13(s[i+8])^ x9(s[i+12]) for i in range(4)]+ \
[ x9(s[i])^x14(s[i+4])^x11(s[i+8])^x13(s[i+12]) for i in range(4)]+ \
[x13(s[i])^ x9(s[i+4])^x14(s[i+8])^x11(s[i+12]) for i in range(4)]+ \
[x11(s[i])^x13(s[i+4])^ x9(s[i+8])^x14(s[i+12]) for i in range(4)]

def addRoundKey (self,subkey,state):
"""AddRoundKey transformation"""
return [i^j for i,j in zip(subkey,state)]

xorLists = addRoundKey

def rotWord(self,number):
"""Rotate subkey left"""
return (((number&0xff000000)>>24) +
((number&0xff0000)<<8) +
((number&0xff00)<<8) +
((number&0xff)<<8))

def subWord(self,key):
"""Substitute subkeys bytes using S-box"""
return ((AES.sBox[(key>>24)&0xff]<<24) +
(AES.sBox[(key>>16)&0xff]<<16) +
(AES.sBox[(key>>8)&0xff]<<8) +
AES.sBox[key&0xff])

def setKey(self,keySize,key,iv = None):
"""KeyExpansion transformation"""
rcon = (0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1B,0x36)
try:
assert keySize in AES.keySizeTable
except AssertionError:
print("Key size identifier not valid")
sys.exit("ValueError")
try:
assert isinstance(key,int)
except AssertionError:
print("Invalid key")
sys.exit("ValueError")
klen = len("{:02x}".format(key))//2
try:
assert klen <= AES.keySizeTable[keySize]
except AssertionError:
print("Key size mismatch")
sys.exit("ValueError")
try:
assert ((self.cipherMode == "MODE_CBC" and isinstance(iv,int)) or
self.cipherMode == "MODE_ECB")
except AssertionError:
print("IV is mandatory for CBC mode")
sys.exit(ValueError)

if self.cipherMode == "MODE_CBC":
temp = self.intToList(iv)
self.ivEncrypt = copy(temp)
self.ivDecrypt = copy(temp)
nr = AES.numberOfRoundsTable[keySize]
self.numberOfRounds = nr
self.wordSize = AES.wordSizeTable[keySize]
if nr == 10:
nk = 4
keyList = self.intToList(key)
elif nr == 12:
nk = 6
keyList =  self.intToList(key>>64) + \
(self.intToList(key&int("ff"*32,16)))[8:]
else:
nk = 8
keyList =  self.intToList(key>>128) + \
self.intToList(key&int("ff"*64,16))
for index in range(nk):
self.w[index] =  (keyList[4*index]<<24) + \
(keyList[4*index+1]<<16) + \
(keyList[4*index+2]<<8) +\
keyList[4*index+3]
for index in range(nk,self.wordSize):
temp = self.w[index - 1]
if index % nk == 0:
temp = (self.subWord(self.rotWord(temp)) ^
rcon[index//nk]<<24)
elif self.numberOfRounds == 14 and index%nk == 4:
temp = self.subWord(temp)
self.w[index] = self.w[index-nk]^temp
self.keyDefined = True
return

def getKey(self,operation):
"""Return next round subkey for encryption or decryption"""
if operation == "encryption":
for i in range(0,self.wordSize,4):
yield self.wordToState(self.w[i:i+4])
else: # operation = "decryption":
for i in reversed(range(0,self.wordSize,4)):
yield self.wordToState(self.w[i:i+4])

def encryptBlock(self,plaintextBlock):
"""Encrypt a 16-byte block with key already defined"""
key = self.getKey("encryption")
state = self.listToState(plaintextBlock)
state = self.addRoundKey(next(key),state)
for _ in repeat(None,self.numberOfRounds - 1):
state = self.subBytes(state)
state = self.shiftRows(state)
state = self.mixColumns(state)
state = self.addRoundKey(next(key),state)
state = self.subBytes(state)
state = self.shiftRows(state)
state = self.addRoundKey(next(key),state)
return self.stateToList(state)

def decryptBlock(self,ciphertextBlock):
"""Decrypt a 16-byte block with key already defined"""
key = self.getKey("decryption")
state = self.listToState(ciphertextBlock)
state = self.addRoundKey(next(key),state)
for _ in repeat(None,self.numberOfRounds - 1):
state = self.invShiftRows(state)
state = self.invSubBytes(state)
state = self.addRoundKey(next(key),state)
state = self.invMixColumns(state)
state = self.invShiftRows(state)
state = self.invSubBytes(state)
state = self.addRoundKey(next(key),state)
return self.stateToList(state)

def padData(self,data):
"""Add PKCS7 padding to plaintext (or just add bytes to fill a block)"""
paddingLength = 16-(len(data)%16)
if self.padding == "NoPadding":
paddingLength %= 16
if type(data) is bytes:
return data+bytes(list([paddingLength]*paddingLength))
else:
return [ord(s) for s in data]+[paddingLength]*paddingLength

def unpadData(self,byteList):
"""Remove PKCS7 padding (if present) from plaintext"""
if self.padding == "PKCS7Padding":
return "".join(chr(e) for e in byteList[:-byteList[-1]])
else:
return "".join(chr(e) for e in byteList)

def encrypt(self,input):
"""Encrypt plaintext passed as a string or as an integer"""
try:
assert self.keyDefined
except AssertionError:
print("Key not defined")
sys.exit("ValueError")

if type(input) is int:
inList = self.intToList2(input)
else:
inList = self.padData(input)
outList = []
if self.cipherMode == "MODE_CBC":
outBlock = self.ivEncrypt
for i in range(0,len(inList),16):
auxList = self.xorLists(outBlock,inList[i:i+16])
outBlock = self.encryptBlock(auxList)
outList += outBlock
self.ivEncrypt = outBlock
else:
for i in range(0,len(inList),16):
outList += self.encryptBlock(inList[i:i+16])
if type(input) is int:
return self.listToInt(outList)
else:
return outList

def decrypt(self,input):
"""Decrypt ciphertext passed as a string or as an integer"""
try:
assert self.keyDefined
except AssertionError:
print("Key not defined")
sys.exit("ValueError")
if type(input) is int:
inList = self.intToList2(input)
else:
inList = input
outList = []
if self.cipherMode == "MODE_CBC":
oldInBlock = self.ivDecrypt
for i in range(0,len(inList),16):
newInBlock = inList[i:i+16]
auxList = self.decryptBlock(newInBlock)
outList += self.xorLists(oldInBlock,auxList)
oldInBlock = newInBlock
self.ivDecrypt = oldInBlock
else:
for i in range(0,len(inList),16):
outList += self.decryptBlock(inList[i:i+16])
if type(input) is int:
return self.listToInt(outList)
else:
return self.unpadData(outList)
```

The Python program below extracts data from the files contained in the KAT_AES directory, then builds the test cases and finally executes them. Only the files applicable to ECB and CBC operation modes (the modes supported by this AES implementation) are considered.

```#!/usr/bin/python3
#
# Author: Joao H de A Franco (jhafranco@acm.org)
#
# Description: Validation of an AES implementation in Python
#
# Date: 2013-06-02
#
# License: Attribution-NonCommercial-ShareAlike 3.0 Unported
#          (CC BY-NC-SA 3.0)
#===========================================================

import os,sys,re
from functools import reduce
from glob import glob
import sundAES

# Global counters
noFilesTested = noFilesSkipped = 0
counterOK = counterNOK = 0

class AEStester:
""""""
def buildTestCases(self,filename):
"""Build test cases described in a given file"""
global noFilesTested,noFilesSkipped

self.basename = os.path.basename(filename)
if self.basename.startswith('ECB'):
self.mode = "MODE_ECB"
noFilesTested += 1
elif self.basename.startswith('CBC'):
self.mode = "MODE_CBC"
noFilesTested += 1
else:
noFilesSkipped += 1
return

digits = re.search("\d{3}",self.basename)
self.keysize = 'SIZE_' + digits.group()
result = re.search("CFB\d*(\D{6,})\d{3}",self.basename)
if result != None:
self.typeTest = result.group(1)
self.typeTest = re.search("\w{3}(\D{6,})\d{3}",self.basename).group(1)
self.iv = None
for line in open(filename):
line = line.strip()
if (line == "") or line.startswith('#'):
continue
elif line == '[ENCRYPT]':
self.operation = 'encrypt'
continue
elif line == '[DECRYPT]':
self.operation = 'decrypt'
continue
param,_,value = line.split(' ',2)
if param == "COUNT":
self.count = int(value)
continue
else:
self.__setattr__(param.lower(),int(value,16))
if (self.operation == 'encrypt') and (param == "CIPHERTEXT") or \
(self.operation == 'decrypt' and param == "PLAINTEXT"):
self.runTestCase()

def runTestCase(self):
"""Execute test case and report result"""
global counterOK,counterNOK

def printTestCase(result):
print("Type={0:s} Mode={1:s} Keysize={2:s} Function={3:s} Count={4:03d} {5:s}"\
.format(self.typeTest,self.mode[5:],\
self.keysize[5:],self.operation.upper(),\
self.count,result))

obj = sundAES3.AES(self.mode)
obj.setKey(self.keysize,self.key,self.iv)
if self.operation == 'encrypt':
CIPHERTEXT = obj.encrypt(self.plaintext)
try:
assert self.ciphertext == CIPHERTEXT
counterOK += 1
printTestCase("OK")
except AssertionError:
counterNOK +=1
print(self.basename)
printTestCase("failed")
print("Expected ciphertext={0:0x}".format(self.ciphertext))
print("Returned ciphertext={0:0x}".format(CIPHERTEXT))
else:
PLAINTEXT = obj.decrypt(self.ciphertext)
try:
assert self.plaintext == PLAINTEXT
counterOK += 1
printTestCase("OK")
except AssertionError:
counterNOK +=1
print(self.basename)
printTestCase("failed")
print("Expected plaintext={0:0x}".format(self.plaintext))
print("Returned plaintext={0:0x}".format(PLAINTEXT))

# Main program
path = os.path.dirname(__file__)
files = sys.argv[1:]
if not files:
files = glob(os.path.join(path,'KAT_AES','*.rsp'))
files.sort()
for file in files:
AEStester().buildTestCases(file)
print("Files tested={0:d}".format(noFilesTested))
print("Files skipped={0:d}".format(noFilesSkipped))
print("Test cases OK={0:d}".format(counterOK))
print("Test cases NOK={0:d}".format(counterNOK))
```

Executed without arguments, this program will apply all ECB and CBC tests described in the files against the AES implementation, producing the following output:

```Type=GFSbox Mode=CBC Keysize=128 Function=ENCRYPT Count=000 OK
Type=GFSbox Mode=CBC Keysize=128 Function=ENCRYPT Count=001 OK
Type=GFSbox Mode=CBC Keysize=128 Function=ENCRYPT Count=002 OK
Type=GFSbox Mode=CBC Keysize=128 Function=ENCRYPT Count=003 OK
Type=GFSbox Mode=CBC Keysize=128 Function=ENCRYPT Count=004 OK

... (4,147 lines omitted)

Type=VarTxt Mode=ECB Keysize=256 Function=DECRYPT Count=124 OK
Type=VarTxt Mode=ECB Keysize=256 Function=DECRYPT Count=125 OK
Type=VarTxt Mode=ECB Keysize=256 Function=DECRYPT Count=126 OK
Type=VarTxt Mode=ECB Keysize=256 Function=DECRYPT Count=127 OK
Files tested=24
Files skipped=48
Test cases OK=4156
Test cases NOK=0
```

If, however, this program is run with one or more files in the KAT_AES directory as argument(s), it will instead build and execute the tests contained in the indicated file(s).

# AES-GCM implementation in Python 3

Galois/Counter Mode (GCM) is a mode of operation for symmetric key cryptographic block ciphers that provides authenticated encryption.

Proposed by David McGrew and John Viega in 2005, GCM is suited for high-speed secure computing and communication. Acknowledging this fact, the US National Institute of Standards and Technology (NIST) standardized GCM and its companion algorithm, Galois Message Authentication Code (GMAC), in 2007. The latter is an authentication-only variant of GCM which can be used as an incremental message authentication code (MAC). AES-GCM (the Advanced Encryption Algorithm operating in Galois/Counter Mode) has also been included in NSA Suite B Cryptography.

GCM’s confidentiality service is based on a variation of the Counter mode (CTR) while its authenticity assurance relies on a universal hash function defined over the binary Galois field $GF(2^{128})/x^{128}+x^7+x^2+x+1$.

GCM is defined for block ciphers with block sizes of 128, 192, and 256 bits (AES uses 128-bit blocks). Both GCM and GMAC can accept initialization vectors (IVs) of arbitrary length (AES and other symmetric ciphers, on the other hand, require IVs to be of the same size as the cipher’s block size).

Its interesting to note that Intel high-end CPUs support a special instruction, PCLMULQDQ, that computes the 128-bit product (the carry-less multiplication) of two 64-bit operands. This instruction can be used as a building block to perform the carry-less multiplication of two 128-bit operands required by GCM. The other step in GCM is reduction modulo the irreducible polynomial $x^{128}+x^7+x^2+x+1$, an operation that takes advantage of the PSRLD, PSLLD and PSHUFD instructions. Together with Intel’s Advanced Encryption Standard Instructions (AES-NI), these instructions allow GCM to offer authenticated encryption services at very high rates without using hardware-based solutions (e.g. FPGAs or ASICs). According to Intel, “an AES-GCM implementation based on the AES-NI and PCLMULQDQ instructions delivered a 400% throughput performance gain when compared to a non-AES-NI enabled software solution on the same platform.”

The Python code below implements AES-GCM using the AES implementation already presented and supports the three key sizes used by AES (128, 192 and 256 bits). All eighteen test cases proposed by McGrew & Viega were used to validate this implementation. Please note that this code is not of production quality.

```#!/usr/bin/python3
#
# Author: Joao H de A Franco (jhafranco@acm.org)
#
# Description: AES-GCM (Galois Counter/Mode) implementation
#              in Python 3
#
# Date: 2013-05-30
#
# License: Attribution-NonCommercial-ShareAlike 3.0 Unported
#          (CC BY-NC-SA 3.0)
#================================================================

import pyAES
from functools import reduce

def xor(x,y):
"""Returns the exclusive or (xor) between two vectors"""
return bytes(i^j for i,j in zip(x,y))

def intToList(number,listSize):
"""Convert a number into a byte list"""
return [(number >> i) & 0xff
for i in reversed(range(0,listSize*8,8))]

def listToInt(list):
"""Convert a byte list into a number"""
return reduce(lambda x,y:(x<<8)+y,list)

def GHASH (hkey,aad,ctext):
"""GCM's GHASH function"""
def xorMultH (p,q):
"""Multiply (p^q) by hash key"""
def multGF2(x,y):
"""Multiply two polynomials in GF(2^m)/g(w)
g(w) = w^128 + w^7 + w^2 + w + 1
(operands and result bits reflected)"""
(x,y) = map(lambda z:listToInt(list(z)),(x,y))
z = 0
while y & ((1<<128)-1):
if y & (1<<127):
z ^= x
y <<= 1
if x & 1:
x = (x>>1)^(0xe1<<120)
else:
x >>= 1
return bytes(intToList(z,16))

return bytes(multGF2(hkey,xor(p,q)))

def gLen(s):
"""Evaluate length of input in bits and returns
it in the LSB bytes of a 64-bit string"""
return bytes(intToList(len(s)*8,8))

x = bytes(16)
aadP = aad + bytes((16-len(aad)%16)%16)
ctextP = ctext + bytes((16-len(ctext)%16)%16)
for i in range(0,len(aadP),16):
x = xorMultH(x,aadP[i:i+16])
for i in range(0,len(ctextP),16):
x = xorMultH(x,ctextP[i:i+16])
return xorMultH(x,gLen(aad) + gLen(ctext))

def GCM_crypt(keysize,key,iv,input,aad):
"""GCM's Authenticated Encryption/Decryption Operations"""
def incr(m):
"""Increment the LSB 32 bits of input counter"""
n = list(m)
n12 = bytes(n[:12])
ctr = listToInt(n[12:])
if ctr == (1<<32)-1:
return n12 + bytes(4)
else:
return n12 + bytes(intToList(ctr+1,4))

obj = pyAES.AES('MODE_ECB')
obj.setKey(keysize,key)
h = bytes(obj.encrypt(bytes(16)))
output = bytes()
L = len(input)
if len(iv) == 12:
y0 = bytes(iv) + bytes(b'\x00\x00\x00\x01')
else:
y0 = bytes(GHASH(h,bytes(),iv))
y = y0
for i in range(0,len(input),16):
y = incr(y)
ctextBlock = xor(bytes(obj.encrypt(y)),
input[i:min(i+16,L)])
output += bytes(ctextBlock)
g = obj.encrypt(y0)
tag = xor(GHASH(h,aad,output),g)
return output,tag,g,h

def GCM_encrypt(keysize,key,iv,ptext,aad):
"""GCM's Authenticated Encryption Operation"""
(ctext,tag,g,h) = GCM_crypt(keysize,key,iv,ptext,aad)
return ctext,xor(GHASH(h,aad,ctext),g)

def GCM_decrypt(keysize,key,iv,ctext,aad,tag):
"""GCM's Authenticated Decryption Operation"""
(ptext,_,g,h) = GCM_crypt(keysize,key,iv,ctext,aad)
if tag == xor(GHASH(h,aad,ctext),g):
return True,ptext
else:
return False,None

######################## Testing section ########################

if __name__ == '__main__':

def printHex(s):
"""Prints a bytes string in hex format"""
print('{0:#0x}'.format(bytesToInt(s)))

def bytesToInt(b):
"""Converts a bytes string into an integer"""
return listToInt(list(b))

def listToInt(list):
"""Convert a byte list into a number"""
return reduce(lambda x,y:(x<<8)+y,list)

def checkTestVector(id,keysize,key,ptext,aad,iv,ctext,tag):
def intToBytes(n):
"""Converts an integer into a bytes string"""
lst = []
while n:
lst.append(n&0xff)
n >>= 8
return bytes(reversed(lst))

def convertType(v):
"""Convert input variable type to bytes"""
if type(v) is int:
return intToBytes(v)
elif type(v) is bytes:
return v
else:
return bytes(v,'ISO-8859-1')

def printOutputs():
"""Prints expected/evaluated tags and
expected/evaluated ciphertexts"""
print("Tag expected:  ", end="")
printHex(tag)
print("Tag evaluated: ", end="")
printHex(TAG)
print("Ciphertext expected:  ", end="")
printHex(ctext)
print("Ciphertext evaluated: ", end="")
printHex(CTEXT)

(ptext,aad,iv,ctext,tag) = map(convertType,(ptext,aad,iv,ctext,tag))
(CTEXT,TAG) = GCM_encrypt(keysize,key,iv,ptext,aad)
(SUCCESS,PTEXT) = GCM_decrypt(keysize,key,iv,CTEXT,aad,TAG)

try:
assert SUCCESS & (CTEXT == ctext) & (TAG == tag)
print("Test case {0:0d} succeeded".format(id))
except AssertionError:
print("Test case {0:0d} failed".format(id))
printOutputs()

# Test cases extracted from
# "The Galois/Counter Mode of Operation(GCM)", McGrew & Viega, 2005 (http://goo.gl/DWJPK)

# Some useful constants
emptyString = bytes() # zero length bit string
nullBitString128 = bytes(16) # 128-bit null string
nullBitString96 = bytes(12) # 96-bit null IV

# Test Case #1
testcase1 = {'id':1,'keysize':"SIZE_128",'key':0x0,'ptext':emptyString,
'aad':emptyString,'iv':nullBitString96,'ctext':emptyString,
'tag':0x58e2fccefa7e3061367f1d57a4e7455a}

# Test Case #2
testcase2 = {'id':2,'keysize':"SIZE_128",'key':0x0,'ptext':nullBitString128,
'aad':emptyString,'iv':nullBitString96,'ctext':0x0388dace60b6a392f328c2b971b2fe78,
'tag':0xab6e47d42cec13bdf53a67b21257bddf}

# Test Case #3
testcase3 = {'id':3,'keysize':"SIZE_128",'key':0xfeffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255,
'aad':emptyString,'iv':0xcafebabefacedbaddecaf888,
'ctext':0x42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985,
'tag':0x4d5c2af327cd64a62cf35abd2ba6fab4}

## Test Case #4
testcase4 = {'id':4,'keysize':"SIZE_128",'key':0xfeffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,'iv':0xcafebabefacedbaddecaf888,
'ctext':0x42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091,
'tag':0x5bc94fbc3221a5db94fae95ae7121a47}

## Test Case #5
testcase5 = {'id':5,'keysize':"SIZE_128",'key':0xfeffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,'iv':0xcafebabefacedbad,
'ctext':0x61353b4c2806934a777ff51fa22a4755699b2a714fcdc6f83766e5f97b6c742373806900e49f24b22b097544d4896b424989b5e1ebac0f07c23f4598,
'tag':0x3612d2e79e3b0785561be14aaca2fccb}

## Test Case #6
testcase6 = {'id':6,'keysize':"SIZE_128",'key':0xfeffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,
'iv':0x09313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b525416aedbf5a0de6a57a637b39b,
'ctext':0x8ce24998625615b603a033aca13fb894be9112a5c3a211a8ba262a3cca7e2ca701e4a9a4fba43c90ccdcb281d48c7c6fd62875d2aca417034c34aee5,
'tag':0x619cc5aefffe0bfa462af43c1699d050}

## Test Case #7
testcase7 = {'id':7,'keysize':"SIZE_192",'key':0x0,'ptext':emptyString,
'aad':emptyString,'iv':nullBitString96,'ctext':emptyString,
'tag':0xcd33b28ac773f74ba00ed1f312572435}

## Test Case #8
testcase8 = {'id':8,'keysize':"SIZE_192",'key':0x0,'ptext':nullBitString128,
'aad':emptyString,'iv':nullBitString96,
'ctext':0x98e7247c07f0fe411c267e4384b0f600,
'tag':0x2ff58d80033927ab8ef4d4587514f0fb}

## Test Case #9
testcase9 = {'id':9,'keysize':"SIZE_192",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255,
'aad':emptyString,'iv':0xcafebabefacedbaddecaf888,
'ctext':0x3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710acade256,
'tag':0x9924a7c8587336bfb118024db8674a14}

## Test Case #10
testcase10 = {'id':10,'keysize':"SIZE_192",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,'iv':0xcafebabefacedbaddecaf888,
'ctext':0x3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710,
'tag':0x2519498e80f1478f37ba55bd6d27618c}

## Test Case #11
testcase11 = {'id':11,'keysize':"SIZE_192",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,'iv':0xcafebabefacedbad,
'ctext':0x0f10f599ae14a154ed24b36e25324db8c566632ef2bbb34f8347280fc4507057fddc29df9a471f75c66541d4d4dad1c9e93a19a58e8b473fa0f062f7,
'tag':0x65dcc57fcf623a24094fcca40d3533f8}

## Test Case #12
testcase12 = {'id':12,'keysize':"SIZE_192",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,
'iv':0x9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b525416aedbf5a0de6a57a637b39b,
'ctext':0xd27e88681ce3243c4830165a8fdcf9ff1de9a1d8e6b447ef6ef7b79828666e4581e79012af34ddd9e2f037589b292db3e67c036745fa22e7e9b7373b,
'tag':0xdcf566ff291c25bbb8568fc3d376a6d9}

## Test Case #13
testcase13 = {'id':13,'keysize':"SIZE_256",'key':0x0,'ptext':emptyString,
'aad':emptyString,'iv':nullBitString96,'ctext':emptyString,
'tag':0x530f8afbc74536b9a963b4f1c4cb738b}

## Test Case #14
testcase14 = {'id':14,'keysize':"SIZE_256",'key':0x0,'ptext':nullBitString128,
'aad':emptyString,'iv':nullBitString96,'ctext':0xcea7403d4d606b6e074ec5d3baf39d18,
'tag':0xd0d1c8a799996bf0265b98b5d48ab919}

## Test Case #15
testcase15 = {'id':15,'keysize':"SIZE_256",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255,
'aad':emptyString,'iv':0xcafebabefacedbaddecaf888,
'ctext':0x522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad,
'tag':0xb094dac5d93471bdec1a502270e3cc6c}

## Test Case #16
testcase16 = {'id':16,'keysize':"SIZE_256",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,'iv':0xcafebabefacedbaddecaf888,
'ctext':0x522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662,
'tag':0x76fc6ece0f4e1768cddf8853bb2d551b}

## Test Case #17
testcase17 = {'id':17,'keysize':"SIZE_256",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,'iv':0xcafebabefacedbad,
'ctext':0xc3762df1ca787d32ae47c13bf19844cbaf1ae14d0b976afac52ff7d79bba9de0feb582d33934a4f0954cc2363bc73f7862ac430e64abe499f47c9b1f,
'tag':0x3a337dbf46a792c45e454913fe2ea8f2}

## Test Case #18
testcase18 = {'id':18,'keysize':"SIZE_256",'key':0xfeffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308,
'ptext':0xd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39,
'aad':0xfeedfacedeadbeeffeedfacedeadbeefabaddad2,
'iv':0x9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b525416aedbf5a0de6a57a637b39b,
'ctext':0x5a8def2f0c9e53f1f75d7853659e2a20eeb2b22aafde6419a058ab4f6f746bf40fc0c3b780f244452da3ebf1c5d82cdea2418997200ef82e44ae7e3f,
'tag':0xa44a8266ee1c8eb0c8b5d4cf5ae9f19a}

for i in range(1,19):
checkTestVector(**(eval("testcase" + str(i))))
```

# Simplified AES implementation in Python

Simplified AES, created by Edward Schaefer and two of his students at Santa Clara University in 2003, is described in the paper “A Simplified AES Algorithm and Its Linear and Differential Cryptoanalyses”, Cryptologia, Vol. XXVII (2), pages 148-177. Like Simplified DES, its purpose is educational, since its key and block size are very small (16-bit and 8-bit, respectively). Nonetheless, due to its simplicity, it is possible for students to encrypt or decrypt a block doing all operations by hand, making it easier for them to understand the structure and operation of its elder brother, AES.

```#!/usr/bin/python3
#
# Author: Joao H de A Franco (jhafranco@acm.org)
#
# Description: Simplified AES implementation in Python 3
#
# Date: 2012-02-11
#
# License: Attribution-NonCommercial-ShareAlike 3.0 Unported
#          (CC BY-NC-SA 3.0)
#===========================================================
import sys

# S-Box
sBox  = [0x9, 0x4, 0xa, 0xb, 0xd, 0x1, 0x8, 0x5,
0x6, 0x2, 0x0, 0x3, 0xc, 0xe, 0xf, 0x7]

# Inverse S-Box
sBoxI = [0xa, 0x5, 0x9, 0xb, 0x1, 0x7, 0x8, 0xf,
0x6, 0x0, 0x2, 0x3, 0xc, 0x4, 0xd, 0xe]

# Round keys: K0 = w0 + w1; K1 = w2 + w3; K2 = w4 + w5
w = [None] * 6

def mult(p1, p2):
"""Multiply two polynomials in GF(2^4)/x^4 + x + 1"""
p = 0
while p2:
if p2 & 0b1:
p ^= p1
p1 <<= 1
if p1 & 0b10000:
p1 ^= 0b11
p2 >>= 1
return p & 0b1111

def intToVec(n):
"""Convert a 2-byte integer into a 4-element vector"""
return [n >> 12, (n >> 4) & 0xf, (n >> 8) & 0xf,  n & 0xf]

def vecToInt(m):
"""Convert a 4-element vector into 2-byte integer"""
return (m[0] << 12) + (m[2] << 8) + (m[1] << 4) + m[3]

def addKey(s1, s2):
"""Add two keys in GF(2^4)"""
return [i ^ j for i, j in zip(s1, s2)]

def sub4NibList(sbox, s):
"""Nibble substitution function"""
return [sbox[e] for e in s]

def shiftRow(s):
"""ShiftRow function"""
return [s[0], s[1], s[3], s[2]]

def keyExp(key):
"""Generate the three round keys"""
def sub2Nib(b):
"""Swap each nibble and substitute it using sBox"""
return sBox[b >> 4] + (sBox[b & 0x0f] << 4)

Rcon1, Rcon2 = 0b10000000, 0b00110000
w[0] = (key & 0xff00) >> 8
w[1] = key & 0x00ff
w[2] = w[0] ^ Rcon1 ^ sub2Nib(w[1])
w[3] = w[2] ^ w[1]
w[4] = w[2] ^ Rcon2 ^ sub2Nib(w[3])
w[5] = w[4] ^ w[3]

def encrypt(ptext):
"""Encrypt plaintext block"""
def mixCol(s):
return [s[0] ^ mult(4, s[2]), s[1] ^ mult(4, s[3]),
s[2] ^ mult(4, s[0]), s[3] ^ mult(4, s[1])]

state = intToVec(((w[0] << 8) + w[1]) ^ ptext)
state = mixCol(shiftRow(sub4NibList(sBox, state)))
state = addKey(intToVec((w[2] << 8) + w[3]), state)
state = shiftRow(sub4NibList(sBox, state))
return vecToInt(addKey(intToVec((w[4] << 8) + w[5]), state))

def decrypt(ctext):
"""Decrypt ciphertext block"""
def iMixCol(s):
return [mult(9, s[0]) ^ mult(2, s[2]), mult(9, s[1]) ^ mult(2, s[3]),
mult(9, s[2]) ^ mult(2, s[0]), mult(9, s[3]) ^ mult(2, s[1])]

state = intToVec(((w[4] << 8) + w[5]) ^ ctext)
state = sub4NibList(sBoxI, shiftRow(state))
state = iMixCol(addKey(intToVec((w[2] << 8) + w[3]), state))
state = sub4NibList(sBoxI, shiftRow(state))
return vecToInt(addKey(intToVec((w[0] << 8) + w[1]), state))

if __name__ == '__main__':
# Test vectors from "Simplified AES" (Steven Gordon)
# (http://hw.siit.net/files/001283.pdf)

plaintext = 0b1101011100101000
key = 0b0100101011110101
ciphertext = 0b0010010011101100
keyExp(key)
try:
assert encrypt(plaintext) == ciphertext
except AssertionError:
print("Encryption error")
print(encrypt(plaintext), ciphertext)
sys.exit(1)
try:
assert decrypt(ciphertext) == plaintext
except AssertionError:
print("Decryption error")
print(decrypt(ciphertext), plaintext)
sys.exit(1)
print("Test ok!")
sys.exit()
```

# AES implementation in Python

After implementing DES, the next obvious challenge was AES. I was expecting AES code to be simpler to write than DES’ because AES was designed to be implemented in hardware or software, while DES design was geared towards hardware. This time, however, I decided to write an object-oriented API supporting the three different key sizes AES inherited from Rijndael (128-, 192- and 256-bit). In addition, besides the ECB (Electronic Code Book) basic operation mode, this implementation also supports CBC (Cipher Block Chaining) mode.

```#!/usr/bin/python3
#
# Author: Joao H de A Franco (jhafranco@acm.org)
#
# Description: AES implementation in Python 3
# (sundAES)
#
# Date: 2013-06-02 (version 1.1)
#       2012-01-16 (version 1.0)
#
# License: Attribution-NonCommercial-ShareAlike 3.0 Unported
# (CC BY-NC-SA 3.0)
#===========================================================
import sys
from itertools import repeat
from functools import reduce
from copy import copy

__all__ = ["setKey","encrypt","decrypt"]

def memoize(func):
"""Memoization function"""
memo = {}
def helper(x):
if x not in memo:
memo[x] = func(x)
return memo[x]
return helper

def mult(p1,p2):
"""Multiply two polynomials in GF(2^8)/x^8+x^4+x^3+x+1"""
p = 0
while p2:
if p2&0x01:
p ^= p1
p1 <<= 1
if p1&0x100:
p1 ^= 0x1b
p2 >>= 1
return p&0xff

# Auxiliary one-parameter functions defined for memoization
# (to speed up multiplication in GF(2^8))

@memoize
def x2(y):
"""Multiplication by 2"""
return mult(2,y)

@memoize
def x3(y):
"""Multiplication by 3"""
return mult(3,y)

@memoize
def x9(y):
"""Multiplication by 9"""
return mult(9,y)

@memoize
def x11(y):
"""Multiplication by 11"""
return mult(11,y)

@memoize
def x13(y):
"""Multiplication by 13"""
return mult(13,y)

@memoize
def x14(y):
"""Multiplication by 14"""
return mult(14,y)

class AES:
"""Class definition for AES objects"""
keySizeTable = {"SIZE_128":16,
"SIZE_192":24,
"SIZE_256":32}
wordSizeTable = {"SIZE_128":44,
"SIZE_192":52,
"SIZE_256":60}
numberOfRoundsTable = {"SIZE_128":10,
"SIZE_192":12,
"SIZE_256":14}
cipherModeTable = {"MODE_ECB":1,
"MODE_CBC":2}
paddingTable = {"NoPadding":0,
"PKCS7Padding":1}
# S-Box
sBox = (0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,
0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,
0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,
0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,
0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,
0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,
0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,
0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,
0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,
0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,
0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,
0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,
0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,
0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,
0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,
0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,
0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16)
# Inverse S-Box
invSBox = (0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,
0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb,
0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,
0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,
0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,
0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e,
0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,
0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,
0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,
0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,
0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,
0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,
0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,
0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06,
0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,
0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b,
0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,
0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,
0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,
0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,
0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,
0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,
0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,
0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,
0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,
0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f,
0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,
0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,
0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,
0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,
0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,
0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d)

# Instance variables
wordSize = None
w = [None]*60 # Round subkeys list
keyDefined = None # Key definition flag
numberOfRounds = None
cipherMode = None
padding = None # Padding scheme
ivEncrypt = None # Initialization
ivDecrypt = None # vectors

def __init__(self,mode,padding = "NoPadding"):
"""Create a new instance of an AES object"""
try:
assert mode in AES.cipherModeTable
except AssertionError:
print("Cipher mode not supported:",mode)
sys.exit("ValueError")
self.cipherMode = mode
try:
assert padding in AES.paddingTable
except AssertionError:
print("Padding scheme not supported:",padding)
sys.exit(ValueError)
self.padding = padding
self.keyDefined = False

def intToList(self,number):
"""Convert an 16-byte number into a 16-element list"""
return [(number>>i)&0xff for i in reversed(range(0,128,8))]

def intToList2(self,number):
"""Converts an integer into one (or more) 16-element list"""
lst = []
while number:
lst.append(number&0xff)
number >>= 8
m = len(lst)%16
if m == 0 and len(lst) != 0:
return lst[::-1]
else:
return list(bytes(16-m)) + lst[::-1]

def listToInt(self,lst):
"""Convert a list into a number"""
return reduce(lambda x,y:(x<<8)+y,lst)

def wordToState(self,wordList):
"""Convert list of 4 words into a 16-element state list"""
return [(wordList[i]>>j)&0xff
for j in reversed(range(0,32,8)) for i in range(4)]

def listToState(self,list):
"""Convert a 16-element list into a 16-element state list"""
return [list[i+j] for j in range(4) for i in range(0,16,4)]

stateToList = listToState # this function is an involution

def subBytes(self,state):
"""SubBytes transformation"""
return [AES.sBox[e] for e in state]

def invSubBytes(self,state):
"""Inverse SubBytes transformation"""
return [AES.invSBox[e] for e in state]

def shiftRows(self,s):
"""ShiftRows transformation"""
return s[:4]+s[5:8]+s[4:5]+s[10:12]+s[8:10]+s[15:]+s[12:15]

def invShiftRows(self,s):
"""Inverse ShiftRows transformation"""
return s[:4]+s[7:8]+s[4:7]+s[10:12]+s[8:10]+s[13:]+s[12:13]

def mixColumns(self,s):
"""MixColumns transformation"""
return [x2(s[i])^x3(s[i+4])^ s[i+8] ^ s[i+12] for i in range(4)]+ \
[ s[i] ^x2(s[i+4])^x3(s[i+8])^ s[i+12] for i in range(4)]+ \
[ s[i] ^ s[i+4] ^x2(s[i+8])^x3(s[i+12]) for i in range(4)]+ \
[x3(s[i])^ s[i+4] ^ s[i+8] ^x2(s[i+12]) for i in range(4)]

def invMixColumns(self,s):
"""Inverse MixColumns transformation"""
return [x14(s[i])^x11(s[i+4])^x13(s[i+8])^ x9(s[i+12]) for i in range(4)]+ \
[ x9(s[i])^x14(s[i+4])^x11(s[i+8])^x13(s[i+12]) for i in range(4)]+ \
[x13(s[i])^ x9(s[i+4])^x14(s[i+8])^x11(s[i+12]) for i in range(4)]+ \
[x11(s[i])^x13(s[i+4])^ x9(s[i+8])^x14(s[i+12]) for i in range(4)]

def addRoundKey (self,subkey,state):
"""AddRoundKey transformation"""
return [i^j for i,j in zip(subkey,state)]

xorLists = addRoundKey

def rotWord(self,number):
"""Rotate subkey left"""
return (((number&0xff000000)>>24) +
((number&0xff0000)<<8) +
((number&0xff00)<<8) +
((number&0xff)<<8))

def subWord(self,key):
"""Substitute subkeys bytes using S-box"""
return ((AES.sBox[(key>>24)&0xff]<<24) +
(AES.sBox[(key>>16)&0xff]<<16) +
(AES.sBox[(key>>8)&0xff]<<8) +
AES.sBox[key&0xff])

def setKey(self,keySize,key,iv = None):
"""KeyExpansion transformation"""
rcon = (0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1B,0x36)
try:
assert keySize in AES.keySizeTable
except AssertionError:
print("Key size identifier not valid")
sys.exit("ValueError")
try:
assert isinstance(key,int)
except AssertionError:
print("Invalid key")
sys.exit("ValueError")
klen = len("{:02x}".format(key))//2
try:
assert klen <= AES.keySizeTable[keySize]
except AssertionError:
print("Key size mismatch")
sys.exit("ValueError")
try:
assert ((self.cipherMode == "MODE_CBC" and isinstance(iv,int)) or
self.cipherMode == "MODE_ECB")
except AssertionError:
print("IV is mandatory for CBC mode")
sys.exit(ValueError)

if self.cipherMode == "MODE_CBC":
temp = self.intToList(iv)
self.ivEncrypt = copy(temp)
self.ivDecrypt = copy(temp)
nr = AES.numberOfRoundsTable[keySize]
self.numberOfRounds = nr
self.wordSize = AES.wordSizeTable[keySize]
if nr == 10:
nk = 4
keyList = self.intToList(key)
elif nr == 12:
nk = 6
keyList = self.intToList(key>>64) + \
(self.intToList(key&int("ff"*32,16)))[8:]
else:
nk = 8
keyList = self.intToList(key>>128) + \
self.intToList(key&int("ff"*64,16))
for index in range(nk):
self.w[index] = (keyList[4*index]<<24) + \
(keyList[4*index+1]<<16) + \
(keyList[4*index+2]<<8) +\
keyList[4*index+3]
for index in range(nk,self.wordSize):
temp = self.w[index - 1]
if index % nk == 0:
temp = (self.subWord(self.rotWord(temp)) ^
rcon[index//nk]<<24)
elif self.numberOfRounds == 14 and index%nk == 4:
temp = self.subWord(temp)
self.w[index] = self.w[index-nk]^temp
self.keyDefined = True
return

def getKey(self,operation):
"""Return next round subkey for encryption or decryption"""
if operation == "encryption":
for i in range(0,self.wordSize,4):
yield self.wordToState(self.w[i:i+4])
else: # operation = "decryption":
for i in reversed(range(0,self.wordSize,4)):
yield self.wordToState(self.w[i:i+4])

def encryptBlock(self,plaintextBlock):
"""Encrypt a 16-byte block with key already defined"""
key = self.getKey("encryption")
state = self.listToState(plaintextBlock)
state = self.addRoundKey(next(key),state)
for _ in repeat(None,self.numberOfRounds - 1):
state = self.subBytes(state)
state = self.shiftRows(state)
state = self.mixColumns(state)
state = self.addRoundKey(next(key),state)
state = self.subBytes(state)
state = self.shiftRows(state)
state = self.addRoundKey(next(key),state)
return self.stateToList(state)

def decryptBlock(self,ciphertextBlock):
"""Decrypt a 16-byte block with key already defined"""
key = self.getKey("decryption")
state = self.listToState(ciphertextBlock)
state = self.addRoundKey(next(key),state)
for _ in repeat(None,self.numberOfRounds - 1):
state = self.invShiftRows(state)
state = self.invSubBytes(state)
state = self.addRoundKey(next(key),state)
state = self.invMixColumns(state)
state = self.invShiftRows(state)
state = self.invSubBytes(state)
state = self.addRoundKey(next(key),state)
return self.stateToList(state)

def padData(self,data):
"""Add PKCS7 padding to plaintext (or just add bytes to fill a block)"""
paddingLength = 16-(len(data)%16)
if self.padding == "NoPadding":
paddingLength %= 16
if type(data) is bytes:
return data+bytes(list([paddingLength]*paddingLength))
else:
return [ord(s) for s in data]+[paddingLength]*paddingLength

def unpadData(self,byteList):
"""Remove PKCS7 padding (if present) from plaintext"""
if self.padding == "PKCS7Padding":
return "".join(chr(e) for e in byteList[:-byteList[-1]])
else:
return "".join(chr(e) for e in byteList)

def encrypt(self,input):
"""Encrypt plaintext passed as a string or as an integer"""
try:
assert self.keyDefined
except AssertionError:
print("Key not defined")
sys.exit("ValueError")

if type(input) is int:
inList = self.intToList2(input)
else:
inList = self.padData(input)
outList = []
if self.cipherMode == "MODE_CBC":
outBlock = self.ivEncrypt
for i in range(0,len(inList),16):
auxList = self.xorLists(outBlock,inList[i:i+16])
outBlock = self.encryptBlock(auxList)
outList += outBlock
self.ivEncrypt = outBlock
else:
for i in range(0,len(inList),16):
outList += self.encryptBlock(inList[i:i+16])
if type(input) is int:
return self.listToInt(outList)
else:
return outList

def decrypt(self,input):
"""Decrypt ciphertext passed as a string or as an integer"""
try:
assert self.keyDefined
except AssertionError:
print("Key not defined")
sys.exit("ValueError")
if type(input) is int:
inList = self.intToList2(input)
else:
inList = input
outList = []
if self.cipherMode == "MODE_CBC":
oldInBlock = self.ivDecrypt
for i in range(0,len(inList),16):
newInBlock = inList[i:i+16]
auxList = self.decryptBlock(newInBlock)
outList += self.xorLists(oldInBlock,auxList)
oldInBlock = newInBlock
self.ivDecrypt = oldInBlock
else:
for i in range(0,len(inList),16):
outList += self.decryptBlock(inList[i:i+16])
if type(input) is int:
return self.listToInt(outList)
else:
return self.unpadData(outList)
```

The code below informally verify the correctness of the implementation with the help of the test vectors described in NIST document SP800-38A, Recommendation for Block Cipher Modes of Operation – Methods and Techniques:

```import pyAES

def intToList(number):
"""Convert a 16-byte number into a 16-element list"""
return [(number >> 120) & 0xff, (number >> 112) & 0xff,
(number >> 104) & 0xff, (number >> 96)  & 0xff,
(number >> 88)  & 0xff, (number >> 80)  & 0xff,
(number >> 72)  & 0xff, (number >> 64)  & 0xff,
(number >> 56)  & 0xff, (number >> 48)  & 0xff,
(number >> 40)  & 0xff, (number >> 32)  & 0xff,
(number >> 24)  & 0xff, (number >> 16)  & 0xff,
(number >> 8)   & 0xff,  number & 0xff]

def intToText(hexNumber):
"""Convert a 16-byte number into a 16 char text string"""
return "".join(chr(e) for e in intToList(hexNumber))

def checkTestVector1(mode, keySize, key, plaintext, ciphertext, iv = None):
"""Check test vectors for single block encryption and decryption"""
success = True
obj = pyAES.AES(mode)
obj.setKey(keySize, key, iv)
for i, (p, c) in enumerate(zip(plaintext, ciphertext)):
p_text = intToText(p)
c_text = intToList(c)
code = "{0:3s}-{1:3s}".format(mode[5:], keySize[5:])
try:
assert obj.encrypt(p_text) == c_text
except AssertionError:
print(code, "encryption #{:d} failed".format(i))
success = False
try:
assert obj.decrypt(c_text) == p_text
except AssertionError:
print(code, "decryption #{:d} failed".format(i))
success = False
if success:
print(code, "encryption/decryption ok")
return success

def checkTestVector2(mode, keySize, plaintext, key1, key2, iv1 = None, iv2 = None):
obj1 = pyAES.AES(mode, "PKCS5Padding")
obj1.setKey(keySize, key1, iv1)
obj2 = pyAES.AES(mode, "PKCS5Padding")
obj2.setKey(keySize, key2, iv2)
ciphertext1 = obj1.encrypt(plaintext)
ciphertext2 = obj2.encrypt(plaintext)
plaintext1 = obj1.decrypt(ciphertext1)
plaintext2 = obj2.decrypt(ciphertext2)
code = "{0:3s}-{1:3s}".format(mode[5:], keySize[5:])
try:
assert plaintext1 == plaintext and plaintext2 == plaintext
except AssertionError:
print("Multi-block", code, "encryption/decryption failed")
return False
print("Multi-block", code, "encryption/decryption ok")
return True

#===========================================================================

# Test vectors from NIST SP800-38A sections F.1.1 and F.1.2
def ECB_128_NOPAD():
key = 0x2b7e151628aed2a6abf7158809cf4f3c
plaintext =  [0x6bc1bee22e409f96e93d7e117393172a,
0xae2d8a571e03ac9c9eb76fac45af8e51,
0x30c81c46a35ce411e5fbc1191a0a52ef,
0xf69f2445df4f9b17ad2b417be66c3710]
ciphertext = [0x3ad77bb40d7a3660a89ecaf32466ef97,
0xf5d3d58503b9699de785895a96fdbaaf,
0x43b1cd7f598ece23881b00e3ed030688,
0x7b0c785e27e8ad3f8223207104725dd4]
return checkTestVector1("MODE_ECB", "SIZE_128", key, plaintext, ciphertext)

# Test vectors from NIST SP800-38A sections F.1.3 and F.1.4
def ECB_192_NOPAD():
key = 0x8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b
plaintext =  [0x6bc1bee22e409f96e93d7e117393172a,
0xae2d8a571e03ac9c9eb76fac45af8e51,
0x30c81c46a35ce411e5fbc1191a0a52ef,
0xf69f2445df4f9b17ad2b417be66c3710]
ciphertext = [0xbd334f1d6e45f25ff712a214571fa5cc,
0x974104846d0ad3ad7734ecb3ecee4eef,
0xef7afd2270e2e60adce0ba2face6444e,
0x9a4b41ba738d6c72fb16691603c18e0e]
return checkTestVector1("MODE_ECB", "SIZE_192", key, plaintext, ciphertext)

# Test vectors from NIST SP800-38A sections F.1.5 and F.1.6
def ECB_256_NOPAD():
key = 0x603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4
plaintext =  [0x6bc1bee22e409f96e93d7e117393172a,
0xae2d8a571e03ac9c9eb76fac45af8e51,
0x30c81c46a35ce411e5fbc1191a0a52ef,
0xf69f2445df4f9b17ad2b417be66c3710]
ciphertext = [0xf3eed1bdb5d2a03c064b5a7e3db181f8,
0x591ccb10d410ed26dc5ba74a31362870,
0xb6ed21b99ca6f4f9f153e7b1beafed1d,
0x23304b7a39f9f3ff067d8d8f9e24ecc7]
return checkTestVector1("MODE_ECB", "SIZE_256", key, plaintext, ciphertext)

# Test vectors from NIST SP800-38A sections F.2.1 and F.2.2
def CBC_128_NOPAD():
key = 0x2b7e151628aed2a6abf7158809cf4f3c
iv = 0x000102030405060708090a0b0c0d0e0f
plaintext =  [0x6bc1bee22e409f96e93d7e117393172a,
0xae2d8a571e03ac9c9eb76fac45af8e51,
0x30c81c46a35ce411e5fbc1191a0a52ef,
0xf69f2445df4f9b17ad2b417be66c3710]
ciphertext = [0x7649abac8119b246cee98e9b12e9197d,
0x5086cb9b507219ee95db113a917678b2,
0x73bed6b8e3c1743b7116e69e22229516,
0x3ff1caa1681fac09120eca307586e1a7]
return checkTestVector1("MODE_CBC", "SIZE_128", key, plaintext, ciphertext, iv)

# Test vectors from NIST SP800-38A sections F.2.3 and F.2.4
def CBC_192_NOPAD():
key = 0x8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b
iv = 0x000102030405060708090a0b0c0d0e0f
plaintext =  [0x6bc1bee22e409f96e93d7e117393172a,
0xae2d8a571e03ac9c9eb76fac45af8e51,
0x30c81c46a35ce411e5fbc1191a0a52ef,
0xf69f2445df4f9b17ad2b417be66c3710]
ciphertext = [0x4f021db243bc633d7178183a9fa071e8,
0xb4d9ada9ad7dedf4e5e738763f69145a,
0x571b242012fb7ae07fa9baac3df102e0,
0x08b0e27988598881d920a9e64f5615cd]
return checkTestVector1("MODE_CBC", "SIZE_192", key, plaintext, ciphertext, iv)

# Test vectors from NIST SP800-38A sections F.2.5 and F.2.6
def CBC_256_NOPAD():
key = 0x603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4
iv = 0x000102030405060708090a0b0c0d0e0f
plaintext=  [0x6bc1bee22e409f96e93d7e117393172a,
0xae2d8a571e03ac9c9eb76fac45af8e51,
0x30c81c46a35ce411e5fbc1191a0a52ef,
0xf69f2445df4f9b17ad2b417be66c3710]
ciphertext = [0xf58c4c04d6e5f1ba779eabfb5f7bfbd6,
0x9cfc4e967edb808d679f777bc6702c7d,
0x39f23369a9d9bacfa530e26304231461,
0xb2eb05e2c39be9fcda6c19078c6a9d1b]
return checkTestVector1("MODE_CBC", "SIZE_256", key, plaintext, ciphertext, iv)

#===========================================================================

# Two multi-block encryptions in ECB mode with 128-bit key
def ECB_128_PKCS5():
plaintext = "The quick brown fox jumps over the lazy dog"
key1 = 0x000102030405060708090a0b0c0d0e0f
key2 = 0xffeeddccbbaa99887766554433221100
return checkTestVector2("MODE_ECB", "SIZE_128", plaintext, key1, key2)

# Two multi-block encryptions in ECB mode with 192-bit key
def ECB_192_PKCS5():
plaintext = "The quick brown fox jumps over the lazy dog"
key1 = 0x000102030405060708090a0b0c0d0e0f1011121314151617
key2 = 0x1716151413121110ffeeddccbbaa99887766554433221100
return checkTestVector2("MODE_ECB", "SIZE_192", plaintext, key1, key2)

# Two multi-block encryptions in ECB mode with 256-bit key
def ECB_256_PKCS5():
plaintext = "The quick brown fox jumps over the lazy dog"
key1 = 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
key2 = 0x1f1e1d1c1b1a19181716151413121110ffeeddccbbaa99887766554433221100
return checkTestVector2("MODE_ECB", "SIZE_256", plaintext, key1, key2)

# Two multi-block encryptions in CBC mode with 128-bit key
def CBC_128_PKCS5():
plaintext = "The quick brown fox jumps over the lazy dog"
key1 = 0x000102030405060708090a0b0c0d0e0f
key2 = 0xffeeddccbbaa99887766554433221100
iv1 = 0x0123cdef456789ab0123cdef456789ab
iv2 = 0xab0123cdef456789ab0123cdef456789
return checkTestVector2("MODE_CBC", "SIZE_128", plaintext, key1, key2, iv1, iv2)

# Two multi-block encryptions in CBC mode with 192-bit key
def CBC_192_PKCS5():
plaintext = "The quick brown fox jumps over the lazy dog"
key1 = 0x000102030405060708090a0b0c0d0e0f1011121314151617
key2 = 0x1716151413121110ffeeddccbbaa99887766554433221100
iv1 = 0x0123cdef456789ab0123cdef456789ab
iv2 = 0xab0123cdef456789ab0123cdef456789
return checkTestVector2("MODE_CBC", "SIZE_192", plaintext, key1, key2, iv1, iv2)

# Two multi-block encryptions in CBC mode with 256-bit key
def CBC_256_PKCS5():
plaintext = "The quick brown fox jumps over the lazy dog"
key1 = 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
key2 = 0x1f1e1d1c1b1a19181716151413121110ffeeddccbbaa99887766554433221100
iv1 = 0x0123cdef456789ab0123cdef456789ab
iv2 = 0xab0123cdef456789ab0123cdef456789
return checkTestVector2("MODE_CBC", "SIZE_256", plaintext, key1, key2, iv1, iv2)

def main():
# Perform vector tests
testSuccess = True
for pad in ["NOPAD", "PKCS5"]:
for mode in ["ECB", "CBC"]:
for size in ["128", "192", "256"]:
testVector = mode + "_" + size + "_" + pad + "()"
testSuccess = testSuccess & eval(testVector)
if testSuccess:
print("All tests passed!")

if __name__ == '__main__':
main()
```