TEA加解密基本算法

def tea_encrypt(v, k):
    # TEA加密
    delta = 0x9e3779b9
    sum = 0
    v0, v1 = v[0], v[1]

    for _ in range(32):
        sum += delta
        v0 += ((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >> 5) + k[1])
        v1 += ((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >> 5) + k[3])

    return v0, v1

def tea_decrypt(v, k):
    # TEA解密
    delta = 0x9e3779b9
    sum = delta * 32
    v0, v1 = v[0], v[1]

    for _ in range(32):
        v1 -= ((v0 << 4) + k[2]) ^ (v0 + sum) ^ ((v0 >> 5) + k[3])
        v0 -= ((v1 << 4) + k[0]) ^ (v1 + sum) ^ ((v1 >> 5) + k[1])
        sum -= delta

    return v0, v1

# 示例加密
plain_data = [12, 23]  # 原始数据
key = [1, 2, 3, 4]  # 密钥

encrypted_data = tea_encrypt(plain_data, key)
print("Encrypted Data:", encrypted_data)

# 示例解密
decrypted_data = tea_decrypt(encrypted_data, key)
print("Decrypted Data:", decrypted_data)

 

posted @ 2023-12-25 10:21  wakappxc  阅读(107)  评论(0编辑  收藏  举报