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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| import random import math
def fastExpMod(b, e, m): result = 1 e = int(e) while e != 0: if e % 2 != 0: e -= 1 result = (result * b) % m continue e >>= 1 b = (b * b) % m return result
def miller_rabin_test(n): p = n - 1 r = 0 while p % 2 == 0: r += 1 p /= 2 b = random.randint(2, n - 2) if fastExpMod(b, int(p), n) == 1: return True for i in range(0, 7): if fastExpMod(b, (2 ** i) * p, n) == n - 1: return True return False
def create_prime_num(keylength): while True: n = random.randint(0, keylength) if n % 2 != 0: found = True for i in range(0, 10): if miller_rabin_test(n): pass else: found = False break if found: return n
def create_keys(keylength): p = create_prime_num(keylength / 2) q = create_prime_num(keylength / 2) n = p * q fn = (p - 1) * (q - 1) e = selectE(fn, keylength / 2) d = match_d(e, fn) return (n, e, d)
def selectE(fn, halfkeyLength): while True: e = random.randint(0, fn) if math.gcd(e, fn) == 1: return e
def match_d(e, fn): d = 0 while True: if (e * d) % fn == 1: return d d += 1
def encrypt(M, e, n): return fastExpMod(M, e, n)
def decrypt(C, d, m): return fastExpMod(C, d, m)
def display(): print("_________________RSA_________________") print("1.encrypt") print("2.decrypt") print("q.quit") print("Enter the key you wanna try") print("_____________________________________")
def encrypt_file(): f = open('明文.txt', "r") mess = f.read() f.close() n, e, d = create_keys(1024) print("请妥善保管私钥(解密时需要用到):(n:", n, " ,d:", d, ")") s = '' print(mess) for ch in mess: c = chr(encrypt(ord(ch), e, n)) s += c f = open("密文.txt", "w", encoding='utf-8') f.write(str(s)) print("Encrypt Done!")
def decrypt_file(): f = open('./pass.txt', 'rb') mess = f.read().decode('utf-8') f.close() n, d = map(int, input("输入您的私钥(n,d):").split()) s = '' for ch in mess: c = chr(decrypt(ord(ch), d, n)) s += c f = open("解密.txt", "w", encoding='utf-8') f.write(str(s)) print("Decrypt Done!")
if __name__ == '__main__': display() while True: c = input(">>>") if c == '1': encrypt_file() if c == '2': decrypt_file() if c == 'q': exit(0) display()
|