PSI的python 实现
时间: 2024-05-07 19:22:52 浏览: 11
PSI(Private Set Intersection)是一种协议,用于两个私有数据集之间寻找共同元素,而不需要泄露数据集本身。下面是一个使用Python实现PSI的简单示例,其中使用了pyfhel库来进行同态加密:
```python
import pyfhel
import random
# 初始化HE上下文和密钥
print("生成密钥...")
HEcontext = pyfhel.FHEContext()
HEcontext.generateFHESecKey(p=2**13, m=2**10)
HEcontext.makeFHEContext()
pubkey = HEcontext.getPublicKey()
seckey = HEcontext.getSecretKey()
# 加密集合A和B中的元素
print("加密集合...")
A = [random.randint(0, 1000) for _ in range(100)]
B = [random.randint(0, 1000) for _ in range(100)]
enc_A = [pubkey.encrypt(x) for x in A]
enc_B = [pubkey.encrypt(x) for x in B]
# 构建哈希表
print("构建哈希表...")
hash_table = {}
for i in range(len(enc_A)):
hash_table[enc_A[i]] = i
# 进行PSI计算
print("计算PSI...")
result = []
for i in range(len(enc_B)):
if enc_B[i] in hash_table:
result.append(B[i])
# 解密结果
print("解密结果...")
decryptor = HEcontext.decryptor()
dec_result = [decryptor.decrypt(x) for x in result]
print("PSI结果:", dec_result)
```
在以上代码中,我们首先生成了HE上下文和密钥,并使用pyfhel库来进行同态加密。然后,我们生成了两个随机的集合A和B,并对它们进行加密。接着,我们构建了一个哈希表,用于快速查找集合A中的元素。最后,我们遍历集合B中的元素,如果它们也在集合A中,则将其添加到结果列表中。最后,我们对结果进行解密,并输出PSI的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)