import struct
import time

def xtea_encrypt(key,data):

    v0,v1 = data    
    sum,delta,mask = 0,0x9e3779b9,0xffffffff
    for round in range(32):
        v0 = (v0 + (((v1<<4 ^ v1>>5) + v1) ^ (sum + key[sum & 3]))) & mask
        sum = (sum + delta) & mask
        v1 = (v1 + (((v0<<4 ^ v0>>5) + v0) ^ (sum + key[sum>>11 & 3]))) & mask

    return [v0,v1]

def xtea_decrypt(key,block):

    v0,v1 = block
    delta,mask = 0x9e3779b9,0xffffffff
    sum = (delta * 32) & mask

    for round in range(32):
        v1 = (v1 - (((v0<<4 ^ v0>>5) + v0) ^ (sum + key[sum>>11 & 3]))) & mask
        sum = (sum - delta) & mask
        v0 = (v0 - (((v1<<4 ^ v1>>5) + v1) ^ (sum + key[sum & 3]))) & mask

    return [v0,v1]


def xtea_test(gnjAPI, dngNr):

    print( "\n     ***** XTEA Test *****")
    time.sleep(2)

    print("      ---- Write xtea key ----")

    key =  [1111122222, 1111133333,2222244444, 2222255555]
    print ("     ", key)
    time.sleep(2)

    #
    # Write Encryption Key
    #
    if gnjAPI.write_key(1234, key, dngNr) > 0:
        print("       ---> WriteKey successful")
    else:
        print("     WriteKey failed")
        return False
    time.sleep(2)

    print("\n      ---- XTEA Encrypt / Decrypt ----")
    time.sleep(2)

    #
    # Encrypt / Decrypt
    #
    data = [ [1234567890, 1234567890],
             [2233445566, 1122445577],
             [1468205773, 934113682],
             [3942612857, 2557492693],
             [2670314019, 1725837151] ]
   
    for d in data:
        print( "\n     original data:", d)

        ret, enc_data = gnjAPI.encrypt_data(1234, d, dngNr)
        if ret > 0:
            print("       --> encrypted by Genji:", enc_data[0] & 0xffffffff,enc_data[1] & 0xffffffff,)

        ret, plain_data = gnjAPI.decrypt_data(1234, enc_data, dngNr)
        if ret > 0:
            print("       --> decrypted by Genji:", plain_data[0]& 0xffffffff , plain_data[1]& 0xffffffff)

        enc_data = xtea_encrypt(  key, d )
        print("       --> encrypted by algorithm:", enc_data)

        dec_data = xtea_decrypt( key, enc_data)
        print("       --> decrypted by algorithm:", dec_data)
    
        print("")
        time.sleep(2)



