Best Python code snippet using molotov_python
aes.py
Source:aes.py  
...127            print("0x%02x " % keys[i + j], end="")128        print("")129        i += 16130#-------------------------------------------------------------------131# print_block()132#133# Print the given block as four 32 bit words.134#-------------------------------------------------------------------135def print_block(block):136    (w0, w1, w2, w3) = block137    print("0x%08x, 0x%08x, 0x%08x, 0x%08x" % (w0, w1, w2, w3))138#-------------------------------------------------------------------139# print_key()140#141# Print the given key as on or two sets of four 32 bit words.142#-------------------------------------------------------------------143def print_key(key):144    if len(key) == 8:145        (k0, k1, k2, k3, k4, k5, k6, k7) = key146        print_block((k0, k1, k2, k3))147        print_block((k4, k5, k6, k7))148    else:149        print_block(key)150#-------------------------------------------------------------------151# b2w()152#153# Create a word from the given bytes.154#-------------------------------------------------------------------155def b2w(b0, b1, b2, b3):156    return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3157#-------------------------------------------------------------------158# w2b()159#160# Extracts the bytes in a word.161#-------------------------------------------------------------------162def w2b(w):163    b0 = w >> 24164    b1 = w >> 16 & 0xff165    b2 = w >> 8 & 0xff166    b3 = w & 0xff167    return (b0, b1, b2, b3)168#-------------------------------------------------------------------169# gm2()170#171# The specific Galois Multiplication by two for a given byte.172#-------------------------------------------------------------------173def gm2(b):174    return ((b << 1) ^ (0x1b & ((b >> 7) * 0xff))) & 0xff175#-------------------------------------------------------------------176# gm3()177#178# The specific Galois Multiplication by three for a given byte.179#-------------------------------------------------------------------180def gm3(b):181    return gm2(b) ^ b182#-------------------------------------------------------------------183# gm4()184#185# The specific Galois Multiplication by four for a given byte.186#-------------------------------------------------------------------187def gm4(b):188    return gm2(gm2(b))189#-------------------------------------------------------------------190# gm8()191#192# The specific Galois Multiplication by eight for a given byte.193#-------------------------------------------------------------------194def gm8(b):195    return gm2(gm4(b))196#-------------------------------------------------------------------197# gm09()198#199# The specific Galois Multiplication by nine for a given byte.200#-------------------------------------------------------------------201def gm09(b):202    return gm8(b) ^ b203#-------------------------------------------------------------------204# gm11()205#206# The specific Galois Multiplication by 11 for a given byte.207#-------------------------------------------------------------------208def gm11(b):209    return gm8(b) ^ gm2(b) ^ b210#-------------------------------------------------------------------211# gm13()212#213# The specific Galois Multiplication by 13 for a given byte.214#-------------------------------------------------------------------215def gm13(b):216    return gm8(b) ^ gm4(b) ^ b217#-------------------------------------------------------------------218# gm14()219#220# The specific Galois Multiplication by 14 for a given byte.221#-------------------------------------------------------------------222def gm14(b):223    return gm8(b) ^ gm4(b) ^ gm2(b)224#-------------------------------------------------------------------225# substw()226#227# Returns a 32-bit word in which each of the bytes in the228# given 32-bit word has been used as lookup into the AES S-box.229#-------------------------------------------------------------------230def substw(w):231    (b0, b1, b2, b3) = w2b(w)232    s0 = sbox[b0]233    s1 = sbox[b1]234    s2 = sbox[b2]235    s3 = sbox[b3]236    res = b2w(s0, s1, s2, s3)237    if VERBOSE:238        print("Inside substw:")239        print("b0 = 0x%02x, b1 = 0x%02x, b2 = 0x%02x, b3 = 0x%02x" %240              (b0, b1, b2, b3))241        print("s0 = 0x%02x, s1 = 0x%02x, s2 = 0x%02x, s3 = 0x%02x" %242              (s0, s1, s2, s3))243        print("res = 0x%08x" % (res))244    return res245#-------------------------------------------------------------------246# inv_substw()247#248# Returns a 32-bit word in which each of the bytes in the249# given 32-bit word has been used as lookup into250# the inverse AES S-box.251#-------------------------------------------------------------------252def inv_substw(w):253    (b0, b1, b2, b3) = w2b(w)254    s0 = inv_sbox[b0]255    s1 = inv_sbox[b1]256    s2 = inv_sbox[b2]257    s3 = inv_sbox[b3]258    res = b2w(s0, s1, s2, s3)259    if VERBOSE:260        print("Inside inv_substw:")261        print("b0 = 0x%02x, b1 = 0x%02x, b2 = 0x%02x, b3 = 0x%02x" %262              (b0, b1, b2, b3))263        print("s0 = 0x%02x, s1 = 0x%02x, s2 = 0x%02x, s3 = 0x%02x" %264              (s0, s1, s2, s3))265        print("res = 0x%08x" % (res))266    return res267#-------------------------------------------------------------------268# rolx()269#270# Rotate the given 32 bit word x bits left.271#-------------------------------------------------------------------272def rolx(w, x):273    return ((w << x) | (w >> (32 - x))) & 0xffffffff274#-------------------------------------------------------------------275# next_128bit_key()276#277# Generate the next four key words for aes-128 based on given278# rcon and previous key words.279#-------------------------------------------------------------------280def next_128bit_key(prev_key, rcon):281    (w0, w1, w2, w3) = prev_key282    rol = rolx(w3, 8)283    subst = substw(rol)284    t = subst ^ (rcon << 24)285    k0 = w0 ^ t286    k1 = w1 ^ w0 ^ t287    k2 = w2 ^ w1 ^ w0 ^ t288    k3 = w3 ^ w2 ^ w1 ^ w0 ^ t289    if VERBOSE:290        print("Inside next 128bit key:")291        print("w0 = 0x%08x, w1 = 0x%08x, w2 = 0x%08x, w3 = 0x%08x" %292              (w0, w1, w2, w3))293        print("rol = 0x%08x, subst = 0x%08x, rcon = 0x%02x, t = 0x%08x" %294              (rol, subst, rcon, t))295        print("k0 = 0x%08x, k1 = 0x%08x, k2 = 0x%08x, k3 = 0x%08x" %296              (k0, k1, k2, k3))297    return (k0, k1, k2, k3)298#-------------------------------------------------------------------299# key_gen128()300#301# Generating the keys for 128 bit keys.302#-------------------------------------------------------------------303def key_gen128(key):304    print("Doing the 128 bit key expansion")305    round_keys = []306    round_keys.append(key)307    for i in range(10):308        round_keys.append(next_128bit_key(round_keys[i], get_rcon(i + 1)))309    if VERBOSE:310        print("Input key:")311        print_block(key)312        print("")313        print("Generated keys:")314        for k in round_keys:315            print_block(k)316        print("")317    return round_keys318#-------------------------------------------------------------------319# next_256bit_key_a()320#321# Generate the next four key words for aes-256 using algorithm A322# based on given rcon and the previous two keys.323#-------------------------------------------------------------------324def next_256it_key_a(key0, key1, rcon):325    (w0, w1, w2, w3) = key0326    (w4, w5, w6, w7) = key1327    sw = substw(rolx(w7, 8))328    rw = (rcon << 24)329    t = sw ^ rw330    k0 = w0 ^ t331    k1 = w1 ^ w0 ^ t332    k2 = w2 ^ w1 ^ w0 ^ t333    k3 = w3 ^ w2 ^ w1 ^ w0 ^ t334    if (DUMP_VARS):335        print("next_256bit_key_a:")336        print("w0 = 0x%08x, w0 = 0x%08x, w0 = 0x%08x, w0 = 0x%08x" % (w0, w1, w2, w3))337        print("w4 = 0x%08x, w5 = 0x%08x, w6 = 0x%08x, w7 = 0x%08x" % (w4, w5, w6, w7))338        print("t = 0x%08x, sw = 0x%08x, rw = 0x%08x" % (t, sw, rw))339        print("k0 = 0x%08x, k0 = 0x%08x, k0 = 0x%08x, k0 = 0x%08x" % (k0, k1, k2, k3))340        print("")341    return (k0, k1, k2, k3)342#-------------------------------------------------------------------343# next_256bit_key_b()344#345# Generate the next four key words for aes-256 using algorithm B346# based on given previous eight keywords.347#-------------------------------------------------------------------348def next_256it_key_b(key0, key1):349    (w0, w1, w2, w3) = key0350    (w4, w5, w6, w7) = key1351    t = substw(w7)352    k0 = w0 ^ t353    k1 = w1 ^ w0 ^ t354    k2 = w2 ^ w1 ^ w0 ^ t355    k3 = w3 ^ w2 ^ w1 ^ w0 ^ t356    if (DUMP_VARS):357        print("next_256bit_key_b:")358        print("w0 = 0x%08x, w0 = 0x%08x, w0 = 0x%08x, w0 = 0x%08x" % (w0, w1, w2, w3))359        print("w4 = 0x%08x, w5 = 0x%08x, w6 = 0x%08x, w7 = 0x%08x" % (w4, w5, w6, w7))360        print("t = 0x%08x" % (t))361        print("k0 = 0x%08x, k0 = 0x%08x, k0 = 0x%08x, k0 = 0x%08x" % (k0, k1, k2, k3))362        print("")363    return (k0, k1, k2, k3)364#-------------------------------------------------------------------365# key_gen256()366#367# Generating the keys for 256 bit keys.368#-------------------------------------------------------------------369def key_gen256(key):370    round_keys = []371    (k0, k1, k2, k3, k4, k5, k6, k7) = key372    round_keys.append((k0, k1, k2, k3))373    round_keys.append((k4, k5, k6, k7))374    j = 1375    for i in range(0, (AES_256_ROUNDS - 2), 2):376        k = next_256it_key_a(round_keys[i], round_keys[i + 1], get_rcon(j))377        round_keys.append(k)378        k = next_256it_key_b(round_keys[i + 1], round_keys[i + 2])379        round_keys.append(k)380        j += 1381    # One final key needs to be generated.382    k = next_256it_key_a(round_keys[12], round_keys[13], get_rcon(7))383    round_keys.append(k)384    if VERBOSE:385        print("Input key:")386        print_block((k0, k1, k2, k3))387        print_block((k4, k5, k6, k7))388        print("")389        print("Generated keys:")390        for k in round_keys:391            print_block(k)392        print("")393    return round_keys394#-------------------------------------------------------------------395# get_rcon()396#397# Function implementation of rcon. Calculates rcon for a398# given round. This could be implemented as an iterator.399#-------------------------------------------------------------------400def get_rcon(round):401    rcon = 0x8d402    for i in range(0, round):403        rcon = ((rcon << 1) ^ (0x11b & - (rcon >> 7))) & 0xff404    return rcon405#-------------------------------------------------------------------406# addroundkey()407#408# AES AddRoundKey block operation.409# Perform XOR combination of the given block and the given key.410#-------------------------------------------------------------------411def addroundkey(key, block):412    (w0, w1, w2, w3) = block413    (k0, k1, k2, k3) = key414    res_block = (w0 ^ k0, w1 ^ k1, w2 ^ k2, w3 ^ k3)415    if VERBOSE:416        print("AddRoundKey key, block in and block out:")417        print_block(key)418        print_block(block)419        print_block(res_block)420        print("")421    return res_block422#-------------------------------------------------------------------423# mixw()424#425# Perform bit mixing of the given words.426#-------------------------------------------------------------------427def mixw(w):428    (b0, b1, b2, b3) = w2b(w)429    mb0 = gm2(b0) ^ gm3(b1) ^ b2      ^ b3430    mb1 = b0      ^ gm2(b1) ^ gm3(b2) ^ b3431    mb2 = b0      ^ b1      ^ gm2(b2) ^ gm3(b3)432    mb3 = gm3(b0) ^ b1      ^ b2      ^ gm2(b3)433    return b2w(mb0, mb1, mb2, mb3)434#-------------------------------------------------------------------435# mixcolumns()436#437# AES MixColumns on the given block.438#-------------------------------------------------------------------439def mixcolumns(block):440    (c0, c1, c2, c3) = block441    mc0 = mixw(c0)442    mc1 = mixw(c1)443    mc2 = mixw(c2)444    mc3 = mixw(c3)445    res_block = (mc0, mc1, mc2, mc3)446    if VERBOSE:447        print("MixColumns block in and block out:")448        print_block(block)449        print_block(res_block)450        print("")451    return res_block452#-------------------------------------------------------------------453# subbytes()454#455# AES SubBytes operation on the given block.456#-------------------------------------------------------------------457def subbytes(block):458    (w0, w1, w2, w3) = block459    res_block = (substw(w0), substw(w1), substw(w2), substw(w3))460    if VERBOSE:461        print("SubBytes block in and block out:")462        print_block(block)463        print_block(res_block)464        print("")465    return res_block466#-------------------------------------------------------------------467# shiftrows()468#469# AES ShiftRows block operation.470#-------------------------------------------------------------------471def shiftrows(block):472    (w0, w1, w2, w3) = block473    c0 = w2b(w0)474    c1 = w2b(w1)475    c2 = w2b(w2)476    c3 = w2b(w3)477    ws0 = b2w(c0[0], c1[1],  c2[2],  c3[3])478    ws1 = b2w(c1[0], c2[1],  c3[2],  c0[3])479    ws2 = b2w(c2[0], c3[1],  c0[2],  c1[3])480    ws3 = b2w(c3[0], c0[1],  c1[2],  c2[3])481    res_block = (ws0, ws1, ws2, ws3)482    if VERBOSE:483        print("ShiftRows block in and block out:")484        print_block(block)485        print_block(res_block)486        print("")487    return res_block488#-------------------------------------------------------------------489# aes_encipher()490#491# Perform AES encipher operation for the given block using the492# given key length.493#-------------------------------------------------------------------494def aes_encipher_block(key, block):495    tmp_block = block[:]496    # Get round keys based on the given key.497    if len(key) == 4:498        round_keys = key_gen128(key)499        num_rounds = AES_128_ROUNDS500    else:501        round_keys = key_gen256(key)502        num_rounds = AES_256_ROUNDS503    # Init round504    print("  Initial AddRoundKeys round.")505    tmp_block4 = addroundkey(round_keys[0], block)506    # Main rounds507    for i in range(1 , (num_rounds)):508        print("")509        print("  Round %02d" % i)510        print("  ---------")511        tmp_block1 = subbytes(tmp_block4)512        tmp_block2 = shiftrows(tmp_block1)513        tmp_block3 = mixcolumns(tmp_block2)514        tmp_block4 = addroundkey(round_keys[i], tmp_block3)515    # Final round516    print("  Final round.")517    tmp_block1 = subbytes(tmp_block4)518    tmp_block2 = shiftrows(tmp_block1)519    tmp_block3 = addroundkey(round_keys[num_rounds], tmp_block2)520    return tmp_block3521#-------------------------------------------------------------------522# inv_mixw()523#524# Perform inverse bit mixing of the given words.525#-------------------------------------------------------------------526def inv_mixw(w):527    (b0, b1, b2, b3) = w2b(w)528    mb0 = gm14(b0) ^ gm11(b1) ^ gm13(b2) ^ gm09(b3)529    mb1 = gm09(b0) ^ gm14(b1) ^ gm11(b2) ^ gm13(b3)530    mb2 = gm13(b0) ^ gm09(b1) ^ gm14(b2) ^ gm11(b3)531    mb3 = gm11(b0) ^ gm13(b1) ^ gm09(b2) ^ gm14(b3)532    return b2w(mb0, mb1, mb2, mb3)533#-------------------------------------------------------------------534# inv_mixcolumns()535#536# AES Inverse MixColumns on the given block.537#-------------------------------------------------------------------538def inv_mixcolumns(block):539    (c0, c1, c2, c3) = block540    mc0 = inv_mixw(c0)541    mc1 = inv_mixw(c1)542    mc2 = inv_mixw(c2)543    mc3 = inv_mixw(c3)544    res_block = (mc0, mc1, mc2, mc3)545    if VERBOSE:546        print("Inverse MixColumns block in and block out:")547        print_block(block)548        print_block(res_block)549        print("")550    return res_block551#-------------------------------------------------------------------552# inv_shiftrows()553#554# AES inverse ShiftRows block operation.555#-------------------------------------------------------------------556def inv_shiftrows(block):557    (w0, w1, w2, w3) = block558    c0 = w2b(w0)559    c1 = w2b(w1)560    c2 = w2b(w2)561    c3 = w2b(w3)562    ws0 = b2w(c0[0], c3[1],  c2[2],  c1[3])563    ws1 = b2w(c1[0], c0[1],  c3[2],  c2[3])564    ws2 = b2w(c2[0], c1[1],  c0[2],  c3[3])565    ws3 = b2w(c3[0], c2[1],  c1[2],  c0[3])566    res_block = (ws0, ws1, ws2, ws3)567    if VERBOSE:568        print("Inverse ShiftRows block in and block out:")569        print_block(block)570        print_block(res_block)571        print("")572    return res_block573#-------------------------------------------------------------------574# inv_subbytes()575#576# AES inverse SubBytes operation on the given block.577#-------------------------------------------------------------------578def inv_subbytes(block):579    (w0, w1, w2, w3) = block580    res_block = (inv_substw(w0), inv_substw(w1), inv_substw(w2), inv_substw(w3))581    if VERBOSE:582        print("Inverse SubBytes block in and block out:")583        print_block(block)584        print_block(res_block)585        print("")586    return res_block587#-------------------------------------------------------------------588# aes_decipher()589#590# Perform AES decipher operation for the given block591# using the given key length.592#-------------------------------------------------------------------593def aes_decipher_block(key, block):594    tmp_block = block[:]595    # Get round keys based on the given key.596    if len(key) == 4:597        round_keys = key_gen128(key)598        num_rounds = AES_128_ROUNDS599    else:600        round_keys = key_gen256(key)601        num_rounds = AES_256_ROUNDS602    # Initial round603    print("  Initial, partial round.")604    tmp_block1 = addroundkey(round_keys[len(round_keys) - 1], tmp_block)605    tmp_block2 = inv_shiftrows(tmp_block1)606    tmp_block4 = inv_subbytes(tmp_block2)607    # Main rounds608    for i in range(1 , (num_rounds)):609        print("")610        print("  Round %02d" % i)611        print("  ---------")612        tmp_block1 = addroundkey(round_keys[(len(round_keys) - i - 1)], tmp_block4)613        tmp_block2 = inv_mixcolumns(tmp_block1)614        tmp_block3 = inv_shiftrows(tmp_block2)615        tmp_block4 = inv_subbytes(tmp_block3)616    # Final round617    print("  Final AddRoundKeys round.")618    res_block = addroundkey(round_keys[0], tmp_block4)619    return res_block620#-------------------------------------------------------------------621# test_mixcolumns()622#623# Test the mixcolumns and inverse mixcolumns operations using624# some simple test values.625#-------------------------------------------------------------------626def test_mixcolumns():627    nist_aes128_key = (0x2b7e1516, 0x28aed2a6, 0xabf71588, 0x09cf4f3c)628    print("Test of mixcolumns and inverse mixcolumns:")629    mixresult = mixcolumns(nist_aes128_key)630    inv_mixresult = inv_mixcolumns(mixresult)631    print("Test of mixw ochi inv_mixw:")632    testw = 0xdb135345633    expw  = 0x8e4da1bc634    mixresult = mixw(testw)635    inv_mixresult = inv_mixw(mixresult)636    print("Testword:   0x%08x" % testw)637    print("expexted:   0x%08x" % expw)638    print("mixword:    0x%08x" % mixresult)639    print("invmixword: 0x%08x" % inv_mixresult)640#-------------------------------------------------------------------641# test_aes()642#643# Test the AES implementation with 128 and 256 bit keys.644#-------------------------------------------------------------------645def test_aes():646    nist_aes128_key = (0x2b7e1516, 0x28aed2a6, 0xabf71588, 0x09cf4f3c)647    nist_aes256_key = (0x603deb10, 0x15ca71be, 0x2b73aef0, 0x857d7781,648                       0x1f352c07, 0x3b6108d7, 0x2d9810a3, 0x0914dff4)649    nist_plaintext0 = (0x6bc1bee2, 0x2e409f96, 0xe93d7e11, 0x7393172a)650    nist_plaintext1 = (0xae2d8a57, 0x1e03ac9c, 0x9eb76fac, 0x45af8e51)651    nist_plaintext2 = (0x30c81c46, 0xa35ce411, 0xe5fbc119, 0x1a0a52ef)652    nist_plaintext3 = (0xf69f2445, 0xdf4f9b17, 0xad2b417b, 0xe66c3710)653    nist_exp128_0 = (0x3ad77bb4, 0x0d7a3660, 0xa89ecaf3, 0x2466ef97)654    nist_exp128_1 = (0xf5d3d585, 0x03b9699d, 0xe785895a, 0x96fdbaaf)655    nist_exp128_2 = (0x43b1cd7f, 0x598ece23, 0x881b00e3, 0xed030688)656    nist_exp128_3 = (0x7b0c785e, 0x27e8ad3f, 0x82232071, 0x04725dd4)657    nist_exp256_0 = (0xf3eed1bd, 0xb5d2a03c, 0x064b5a7e, 0x3db181f8)658    nist_exp256_1 = (0x591ccb10, 0xd410ed26, 0xdc5ba74a, 0x31362870)659    nist_exp256_2 = (0xb6ed21b9, 0x9ca6f4f9, 0xf153e7b1, 0xbeafed1d)660    nist_exp256_3 = (0x23304b7a, 0x39f9f3ff, 0x067d8d8f, 0x9e24ecc7)661    print("Doing block encryption.")662    enc_result128_0 = aes_encipher_block(nist_aes128_key, nist_plaintext0)663    enc_result128_1 = aes_encipher_block(nist_aes128_key, nist_plaintext1)664    enc_result128_2 = aes_encipher_block(nist_aes128_key, nist_plaintext2)665    enc_result128_3 = aes_encipher_block(nist_aes128_key, nist_plaintext3)666    enc_result256_0 = aes_encipher_block(nist_aes256_key, nist_plaintext0)667    enc_result256_1 = aes_encipher_block(nist_aes256_key, nist_plaintext1)668    enc_result256_2 = aes_encipher_block(nist_aes256_key, nist_plaintext2)669    enc_result256_3 = aes_encipher_block(nist_aes256_key, nist_plaintext3)670    print("Doing block decryption.")671    dec_result128_0 = aes_decipher_block(nist_aes128_key, nist_exp128_0)672    dec_result128_1 = aes_decipher_block(nist_aes128_key, nist_exp128_1)673    dec_result128_2 = aes_decipher_block(nist_aes128_key, nist_exp128_2)674    dec_result128_3 = aes_decipher_block(nist_aes128_key, nist_exp128_3)675    dec_result256_0 = aes_decipher_block(nist_aes256_key, nist_exp256_0)676    dec_result256_1 = aes_decipher_block(nist_aes256_key, nist_exp256_1)677    dec_result256_2 = aes_decipher_block(nist_aes256_key, nist_exp256_2)678    dec_result256_3 = aes_decipher_block(nist_aes256_key, nist_exp256_3)679    if VERBOSE:680        print("   AES Encipher tests")681        print("   ==================")682        print("Test 0 for AES-128.")683        print("Key:")684        print_key(nist_aes128_key)685        print("Block in:")686        print_block(nist_plaintext0)687        print("Expected block out:")688        print_block(nist_exp128_0)689        print("Got block out:")690        print_block(enc_result128_0)691        print("")692        print("Test 1 for AES-128.")693        print("Key:")694        print_key(nist_aes128_key)695        print("Block in:")696        print_block(nist_plaintext1)697        print("Expected block out:")698        print_block(nist_exp128_1)699        print("Got block out:")700        print_block(enc_result128_1)701        print("")702        print("Test 2 for AES-128.")703        print("Key:")704        print_key(nist_aes128_key)705        print("Block in:")706        print_block(nist_plaintext2)707        print("Expected block out:")708        print_block(nist_exp128_2)709        print("Got block out:")710        print_block(enc_result128_2)711        print("")712        print("Test 3 for AES-128.")713        print("Key:")714        print_key(nist_aes128_key)715        print("Block in:")716        print_block(nist_plaintext3)717        print("Expected block out:")718        print_block(nist_exp128_3)719        print("Got block out:")720        print_block(enc_result128_3)721        print("")722        print("Test 0 for AES-256.")723        print("Key:")724        print_key(nist_aes256_key)725        print("Block in:")726        print_block(nist_plaintext0)727        print("Expected block out:")728        print_block(nist_exp256_0)729        print("Got block out:")730        print_block(enc_result256_0)731        print("")732        print("Test 1 for AES-256.")733        print("Key:")734        print_key(nist_aes256_key)735        print("Block in:")736        print_block(nist_plaintext1)737        print("Expected block out:")738        print_block(nist_exp256_1)739        print("Got block out:")740        print_block(enc_result256_1)741        print("")742        print("Test 2 for AES-256.")743        print("Key:")744        print_key(nist_aes256_key)745        print("Block in:")746        print_block(nist_plaintext2)747        print("Expected block out:")748        print_block(nist_exp256_2)749        print("Got block out:")750        print_block(enc_result256_2)751        print("")752        print("Test 3 for AES-256.")753        print("Key:")754        print_key(nist_aes256_key)755        print("Block in:")756        print_block(nist_plaintext3)757        print("Expected block out:")758        print_block(nist_exp256_3)759        print("Got block out:")760        print_block(enc_result256_3)761        print("")762        print("")763        print("   AES Decipher tests")764        print("   ==================")765        print("Test 0 for AES-128.")766        print("Key:")767        print_key(nist_aes128_key)768        print("Block in:")769        print_block(nist_exp128_0)770        print("Expected block out:")771        print_block(nist_plaintext0)772        print("Got block out:")773        print_block(dec_result128_0)774        print("")775        print("Test 1 for AES-128.")776        print("Key:")777        print_key(nist_aes128_key)778        print("Block in:")779        print_block(nist_exp128_1)780        print("Expected block out:")781        print_block(nist_plaintext1)782        print("Got block out:")783        print_block(dec_result128_1)784        print("")785        print("Test 2 for AES-128.")786        print("Key:")787        print_key(nist_aes128_key)788        print("Block in:")789        print_block(nist_exp128_2)790        print("Expected block out:")791        print_block(nist_plaintext2)792        print("Got block out:")793        print_block(dec_result128_2)794        print("")795        print("Test 3 for AES-128.")796        print("Key:")797        print_key(nist_aes128_key)798        print("Block in:")799        print_block(nist_exp128_3)800        print("Expected block out:")801        print_block(nist_plaintext3)802        print("Got block out:")803        print_block(dec_result128_3)804        print("")805        print("Test 0 for AES-256.")806        print("Key:")807        print_key(nist_aes256_key)808        print("Block in:")809        print_block(nist_exp256_0)810        print("Expected block out:")811        print_block(nist_plaintext0)812        print("Got block out:")813        print_block(dec_result256_0)814        print("")815        print("Test 1 for AES-256.")816        print("Key:")817        print_key(nist_aes256_key)818        print("Block in:")819        print_block(nist_exp256_1)820        print("Expected block out:")821        print_block(nist_plaintext1)822        print("Got block out:")823        print_block(dec_result256_1)824        print("")825        print("Test 2 for AES-256.")826        print("Key:")827        print_key(nist_aes256_key)828        print("Block in:")829        print_block(nist_exp256_2)830        print("Expected block out:")831        print_block(nist_plaintext2)832        print("Got block out:")833        print_block(dec_result256_2)834        print("")835        print("Test 3 for AES-256.")836        print("Key:")837        print_key(nist_aes256_key)838        print("Block in:")839        print_block(nist_exp256_3)840        print("Expected block out:")841        print_block(nist_plaintext3)842        print("Got block out:")843        print_block(dec_result256_3)844        print("")845#-------------------------------------------------------------------846# main()847#848# If executed tests the ChaCha class using known test vectors.849#-------------------------------------------------------------------850def main():851    print("Testing the AES cipher model")852    print("============================")853    print854    # test_mixcolumns()855    test_aes()856#-------------------------------------------------------------------857# __name__...server.py
Source:server.py  
1# Import socket module2from socket import *345def print_block(line, initial=False, final=False):6    DIVISION_LINE = "\n----------------------------------------------------------------"7    if initial:  # checks if the line is the initial line, if so, it prints a DIVISION_LINE to indicate it is initial8        print(DIVISION_LINE)9    print(" -->  "+line)10    if final:  # checks if the line is the final line, if so, it prints a DIVISION_LINE to indicate it is final11        print(DIVISION_LINE)121314# Receive an initialized socket and listens to possible client connections15def listen(server_socket):16    print('# -- The server is listening -- #')17    connection_Socket, address = server_socket.accept()18    return connection_Socket, address192021# Create a TCP server socket22# (AF_INET is used for IPv4 protocols)23# (SOCK_STREAM is used for TCP)2425serverSocket = socket(AF_INET, SOCK_STREAM)2627# Assign a port number28serverPort = 80  # 67892930# Bind the socket to server address and server port3132serverSocket.bind(("127.8.8.8", serverPort))  # the server listens on the port 80 with the ip 127.8.8.83334# Listen to at most 5 connection at a time35serverSocket.listen(5)3637# sometimes a connection is just for the client to communicate that he received a response, this kind of connection can38# be skipped39skip_connection = False4041# Server should be up and running and listening to the incoming connections42while True:43    if skip_connection:44        skip_connection = not skip_connection45        continue46    # Set up a new connection from the client47    connectionSocket, addr = listen(serverSocket)48    print_block(f"Connection established with address: {addr[0]} on Port: {addr[1]}", initial=True)49    # If an exception occurs during the execution of try clause50    # the rest of the clause is skipped51    # If the exception type matches the word after except52    # the except clause is executed53    try:54        # Receives the request message from the client55        message = connectionSocket.recv(1024).decode()56        if message == "":  # make sure that the message is not empty so that it doesn't throw an error57            print_block("Just a useless connection (Client sent empty message)")58            print_block("Connection with client has been closed", final=True)59            continue60        print_block("GET request received")61        # Extract the path of the requested object from the message62        # The path is the second part of HTTP header, identified by [1]63        # Also, because the extracted path of the HTTP request includes a character '\',64        # we read the path from the second character65        filename = message.split()[1][1:]66        print_block(f"Searching for file: {filename}")67        f = open(filename)68        print_block(f"File: {filename} - found!")69        # Store the entire contenet of the requested file in a temporary buffer70        outputdata = f.read()71        # Send the HTTP response header line to the connection socket72        connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n".encode())73        print_block("HTTP response header sent to client")74        # Send the content of the requested file to the connection socket75        print_block("Sending the content of the requested file to the client - STARTED")76        for i in range(0, len(outputdata)):77            connectionSocket.send(outputdata[i].encode())78        connectionSocket.send("\r\n".encode())79        print_block("Sending the content of the requested file to the client - COMPLETED")80        # Close the client connection socket81        connectionSocket.close()82        print_block("Connection with client has been closed", final=True)8384    except IOError:85        print_block(f"Error: File: {filename} NOT FOUND!!!")86        # Send HTTP response message for file not found87        connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n".encode())88        connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n".encode())89        print_block("Client informed of the Error")90        # Close the client connection socket91        connectionSocket.close()92        print_block("Connection with client has been closed", final=True)939495serverSocket.close()
...DiCECounterfactaulWrapper.py
Source:DiCECounterfactaulWrapper.py  
...11        self.dice_explainer__ = dice_explainer12        self.feature_names = feature_names13    def run_counterfactual_print_result(self, case):14        return_case = deepcopy(case)15        # print_block("", "Finding counterfactuals...")16        input_data = np.array([case["original_vector"]])17        start_time = time()18        input_df = pd.DataFrame(input_data, columns=self.feature_names)19        self.input_df = input_df20        dice_exp = self.dice_explainer__.generate_counterfactuals(input_df, total_CFs=3, desired_class="opposite",21                                                                  # proximity_weight=1.5, diversity_weight=1.022                                                                  )23        self.dice_exp = dice_exp24        end_time = time()25        time_took = end_time - start_time26        # print_block("Time Took", "%.3f sec" % (time_took))27        if len(dice_exp.final_cfs_df) == 0:28            # print_block("", "No counterfactaul found!")29            return_case['cf'] = [None] * input_data.shape[1]30        else:31            # counterfactual = scaler.inverse_transform(list())32            return_case['cf'] = list(dice_exp.final_cfs_df.iloc[0][:-1])33        return_case['time'] = time_took34        # self.print_counterfactual_results(case, counterfactual)35        return return_case36    def print_counterfactual_results(self, case, counterfactual):37        print_block("Prediction type", case["prediction_type"], mark_times=7)38        print_block("Black box prediction", case["predictions"], mark_times=3)39        print_block("Ground truth", case["ground_truth"], mark_times=5)40        print_block("Oringal input", pd.DataFrame(41            [case["original_vector"]], columns=self.feature_names), mark_times=60)42        print_block("Counterfactual", pd.DataFrame(...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
