Created
October 30, 2021 16:54
-
-
Save NWYLZW/dd3b7c54ebef4415467fd4aba872e363 to your computer and use it in GitHub Desktop.
百万富翁问题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json, random, rsa | |
def int_to_bytes(i: int): | |
return i.to_bytes(i.bit_length() + 7, 'big') | |
def bytes_to_int(b: bytes): | |
return int.from_bytes(b, 'big') | |
if __name__ == '__main__': | |
p = 29 | |
sel = input('当前步骤:') | |
if sel == '1': | |
i = int(input('你的工资:')) | |
# 王选取一个公钥 | |
pub_k, pri_k = rsa.newkeys(1024) | |
# 发送给对方 | |
print(pub_k.save_pkcs1().decode('utf-8')) | |
c = int(input('c:')) | |
# 进行解密,得到十个数字。把这十个数字除以 p 的余数数组记作 d | |
d = [ | |
bytes_to_int( | |
rsa.decrypt(int_to_bytes(c_i), pri_k) | |
) % p | |
for c_i in range(c + 1, c + 11) | |
] | |
# 前面 i 个数不动,后面的数字每个加一 | |
for index in range(i, 10): | |
d[index] += 1 | |
print(d) | |
else: | |
# 李选取一个随机的大整数 | |
x = random.randint( | |
1000000, | |
10000000 | |
) | |
j = int(input('你的工资:')) | |
# 用王的公钥加密,得到密文 | |
print('对方公钥:') | |
sentinel = '-----END RSA PUBLIC KEY-----' | |
lines = [] | |
for line in iter(input, sentinel): | |
lines.append(line) | |
lines.append(sentinel) | |
pub_k = '\n'.join(lines) | |
K = rsa.encrypt(int_to_bytes(x), rsa.PublicKey.load_pkcs1(pub_k.encode('utf-8'))) | |
# 发送 K - j 给王 | |
print(bytes_to_int(K) - j) | |
d = json.loads(input('d:')) | |
if x % p == d[j - 1]: | |
print('王有钱,i >= j') | |
else: | |
print('李有钱,i < j') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment