1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| from ctypes import *
def MX(z, y, total, key, p, e): temp1 = (z.value>>5 ^ y.value<<2) + (y.value>>3 ^ z.value<<4) temp2 = (total.value ^ y.value) + (key[(p&3) ^ e.value] ^ z.value) return c_uint32(temp1 ^ temp2)
def encrypt(n, v, key): delta = 0x9e3779b9 rounds = 6 + 52//n
total = c_uint32(0) z = c_uint32(v[n-1]) e = c_uint32(0) while rounds > 0: total.value += delta e.value = (total.value >> 2) & 3 for p in range(n-1): y = c_uint32(v[p+1]) v[p] = c_uint32(v[p] + MX(z,y,total,key,p,e).value).value z.value = v[p] y = c_uint32(v[0]) v[n-1] = c_uint32(v[n-1] + MX(z,y,total,key,n-1,e).value).value z.value = v[n-1] rounds -= 1
return v
def decrypt(n, v, key): delta = 0x9e3779b9 rounds = 6 + 52//n total = c_uint32(rounds * delta) y = c_uint32(v[0]) e = c_uint32(0)
while rounds > 0: e.value = (total.value >> 2) & 3 for p in range(n-1, 0, -1): z = c_uint32(v[p-1]) v[p] = c_uint32((v[p] - MX(z,y,total,key,p,e).value)).value y.value = v[p] z = c_uint32(v[n-1]) v[0] = c_uint32(v[0] - MX(z,y,total,key,0,e).value).value y.value = v[0] total.value -= delta rounds -= 1
return v
if __name__ == "__main__": v = [0x12345678, 0x78563412] k = [0x1, 0x2, 0x3, 0x4] n = 2
print("Data is : ", hex(v[0]), hex(v[1])) res = encrypt(n, v, k) print("Encrypted data is : ", hex(res[0]), hex(res[1])) res = decrypt(n, res, k) print("Decrypted data is : ", hex(res[0]), hex(res[1])) """ Data is : 0x12345678 0x78563412 Encrypted data is : 0xef86c2bb 0x25f31b5e Decrypted data is : 0x12345678 0x78563412 """
|