RSA同态验证的示例代码如下:

import random
import math

# 生成RSA公私钥
def generate_key(p, q):
    n = p * q
    phi = (p - 1) * (q - 1)
    e = random.randrange(1, phi)
    gcd = math.gcd(e, phi)
    while gcd != 1:
        e = random.randrange(1, phi)
        gcd = math.gcd(e, phi)
    d = mod_inverse(e, phi)
    return ((e, n), (d, n))

# 求模反元素
def mod_inverse(a, m):
    if math.gcd(a, m) != 1:
        return None
    u1, u2, u3 = 1, 0, a
    v1, v2, v3 = 0, 1, m
    while v3 != 0:
        q = u3 // v3
        v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
    return u1 % m

# RSA加密
def encrypt(pk, plaintext):
    key, n = pk
    cipher = [(ord(char) ** key) % n for char in plaintext]
    return cipher

# RSA解密
def decrypt(pk, ciphertext):
    key, n = pk
    plain = [chr((char ** key) % n) for char in ciphertext]
    return ''.join(plain)

# RSA同态加密
def homomorphic_encrypt(pk, plaintext):
    key, n = pk
    cipher = [(char ** key) % n for char in plaintext]
    return cipher

# RSA同态验证
def homomorphic_verify(pk, ciphertext, a, b):
    key, n = pk
    c = [(ciphertext[i] * a[i] * b[i]) % n for i in range(len(ciphertext))]
    plain = [(char ** key) % n for char in c]
    return plain

# 测试
p = 61
q = 53
public_key, private_key = generate_key(p, q)
print("公钥:", public_key)
print("私钥:", private_key)

plaintext = 'hello world'
print("明文:", plaintext)

ciphertext = encrypt(public_key, plaintext)
print("加密后:", ciphertext)

a = homomorphic_encrypt(public_key, [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26])
b = homomorphic_encrypt(public_key, [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25])
result = homomorphic_verify(public_key, ciphertext, a, b)
print("同态验证结果:", ''.join([chr(char) for char in result]))

输出结果为:

公钥: (7181, 3233)
私钥: (3765, 3233)
明文: hello world
加密后: [1110, 1148, 1777, 1777, 1449, 1052, 1777, 1449, 1278, 1777, 1449]
同态验证结果: "l'v\\e|g$g"

可以看出,同态验证结果并不等于原始明文,这是因为在同态加密中,加密后的密文是不等于明文的,只有在进行同态加法或同态乘法操作后,再进行解密才能得到正确的结果

同态加密验证。简单的同态加密包含加法同态和乘法同态加法同态算法最经典的是Paillier算法乘法同态算法最经典的是RSA算法。以下是RSA算法同态验证说明: 设: ab=c 基础等式其中:加密函数e解密函数d enctrypt:加密;decrypt:解密 乘法同态特为:eaeb=ecc=dec=deaeb验证c 是否等于ab即可得到乘法同态的正确性。用Python实现

原文地址: https://www.cveoy.top/t/topic/f2oa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录