1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| import re import random import math
def check_package(package): sum=package[0] for i in range(1,len(package)): if sum > package[i]: return False sum += package[i] return True
def is_prime(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else: return False
def selcet_M(package): i = package[-1] * 2 max = i + 10 M = random.randint(i, max) return M
def select_W(M): while True: W = random.randint(0, M) if math.gcd(W, M) == 1: return W
def get_pk(package, W, M): pb_package = [] for b in package: pb_package.append(W * b % M) return pb_package
def encode(): package = input("请输入背包,空格分开元素,格式为1 2 4 8\n> ") package = re.split(r" +", package.strip()) for i in range(len(package)): package[i] = int(package[i]) print(package) if not check_package(package): exit("你的输入不满足超递增背包的条件") M = selcet_M(package) W = select_W(M) public_k = get_pk(package, W, M) print("M:", M, "\nW:", W, "\npublic_k:", public_k) print("secret_k:", package, W, M) message = int(input("请输入待加密数字,应该小于背包容量"+str(sum(package))+"\n> ")) if message>sum(package): exit("你输入的加密数字已大于背包的容纳量,请调整背包大小或者分批输入。") message = list(bin(message)[2:].zfill(len(package))) print(message) for i in range(len(message)): message[i] = int(message[i]) cipher_li = [] for m, k in zip(message, public_k): cipher_li.append(m * k) return sum(cipher_li) % M
def get_niyuan(W, M): niyuan = 1 while (W * niyuan) % M != 1: niyuan += 1 return niyuan
def decode(): cipher = int(input("请输入解密的值\n> ")) print("请输入私钥:W,M,package:") M = int(input("M: ")) W = int(input("W: ")) package = input("package:原背包,空格分开元素,格式为1 2 4 8\n> ") package = re.split(r" +", package.strip()) for i in range(len(package)): package[i] = int(package[i]) print(package) package_sum = get_niyuan(W, M) * cipher % M print("package_sum",package_sum) text = [] for i in reversed(package): if i <= package_sum: text.append("1") package_sum -= i else: text.append("0") return int("".join(reversed(text)), 2)
if __name__ == "__main__": cipher = encode() print("加密后的值为:", cipher) print("-" * 10) message = decode() print("解密后的值为:", message)
|