python代理重加密--通过Umbral实现

一、参考文件:

1.官方文档:pyUmbral官方手册 

2.Umbral:新型分散式密钥管理系统的代理重加密方案

二、环境:

语言:python:3.10

操作系统:windows11

依赖包:pyUmbral:0.3.0(目前最新版本)

安装依赖包: pip install umbral

三、代码

from umbral import SecretKey, Signer

#1.首先,让我们为 Alice 生成两个非对称密钥对:一个委托密钥对和一个签名密钥对。
alices_secret_key = SecretKey.random()
alices_public_key = alices_secret_key.public_key()

alices_signing_key = SecretKey.random()
alices_verifying_key = alices_signing_key.public_key()
alices_signer = Signer(alices_signing_key)

# 2.使用公钥加密
from umbral import encrypt
plaintext = b'Proxy Re-encryption is cool!'
print("\n原始消息:", plaintext.decode())
capsule, ciphertext = encrypt(alices_public_key, plaintext)
print("✅ Alice 加密成功")

# 3.使用私钥解密(可选,实际中不需要本步骤,仅为演示作用)
from umbral import decrypt_original
cleartext = decrypt_original(alices_secret_key, capsule, ciphertext)
print("✅ Alice 私钥解密结果:", cleartext.decode())

# 4.阈值重加密
bobs_secret_key = SecretKey.random()
bobs_public_key = bobs_secret_key.public_key()

# 5.Alice 通过生成 kfrags 授予 Bob 访问权限
from umbral import generate_kfrags
kfrags = generate_kfrags(delegating_sk=alices_secret_key,
                         receiving_pk=bobs_public_key,
                         signer=alices_signer,
                         threshold=10, # 解密所需的最小片段数
                         shares=20 # 生成的片段总数
                         )
print("✅ 重加密密钥生成成功")
#  6.代理节点执行重加密

import random
kfrags = random.sample(kfrags,  # All kfrags from above
                       10)      # M - Threshold

from umbral import reencrypt
cfrags = list()                 # Bob's cfrag collection
for kfrag in kfrags:
    cfrag = reencrypt(capsule=capsule, kfrag=kfrag)
    cfrags.append(cfrag)        # Bob collects a cfrag
print("✅ 代理重加密完成")


# 7.Bob 检查胶囊碎片
from umbral import CapsuleFrag
suspicious_cfrags = [CapsuleFrag.from_bytes(bytes(cfrag)) for cfrag in cfrags]
cfrags = [cfrag.verify(capsule,
                       verifying_pk=alices_verifying_key,
                       delegating_pk=alices_public_key,
                       receiving_pk=bobs_public_key,
                       )
          for cfrag in suspicious_cfrags]
print("✅ Bob 检查成功")
# 8.Bob 打开胶囊

from umbral import decrypt_reencrypted
cleartext = decrypt_reencrypted(receiving_sk=bobs_secret_key,
                                delegating_pk=alices_public_key,
                                capsule=capsule,
                                verified_cfrags=cfrags,
                                ciphertext=ciphertext)
print("\nBob 解密结果:", cleartext.decode())

输出:

原始消息: Proxy Re-encryption is cool!
✅ Alice 加密成功
✅ Alice 私钥解密结果: Proxy Re-encryption is cool!
✅ 重加密密钥生成成功
✅ 代理重加密完成
✅ Bob 检查成功

Bob 解密结果: Proxy Re-encryption is cool!

 

posted @ 2025-07-03 10:44  jiafeng  阅读(18)  评论(0)    收藏  举报