我的数学或我的变量在我的RSA示例中是错误的吗?

时间:2017-08-02 16:47:31

标签: python rsa

我正在阅读密码学,特别是RSA(https://www.khanacademy.org/computing/computer-science/cryptography/modern-crypt/v/rsa-encryption-part-4),并决定为自己做一个例子。然而,尽管我很确定我的变量是正确的,但我认为我的数学错了。有人可以帮我找到错误吗?我试图在任何地方发表评论,我认为需要解释。用Python 3.5.2编写

#m^phi(n) mod n == 1 where m & n dont share a common factor
#since 1^k = 1, m^(k * phi(n)) mod n == 1, too.
#since 1*m = m, m* (m^(k * phi(n)) mod n) == m
#^^^^simplifies to m^(k * phi(n) + 1) mod n == m
#b/c m^(e*d) mod n = m
#m^(e*d) mod n == m^(k * phi(n) + 1) mod n
#e*d = k * phi(n) + 1
#d = (k * phi(n) + 1)/e
from fractions import gcd
import random
i = 1
j = 1
t = 1
def is_prime(a):
    return all(a % i for i in range(2, a))

while True:
    p1 = random.randrange(10.00000)#gens the 1st random prime
    if is_prime(p1):
        if p1 == 0 or p1 == 1:
            i+=1
            continue
        else:
            print("First Random Prime Found on attempt "+str(i)+": "+str(p1))
            break
    i+=1

while True:
    p2 = random.randrange(10.00000)#gens the 1st random prime
    if is_prime(p2):
        if p2 == 0 or p2 == 1:
            j+=1
            continue
        else:
            print("First Random Prime Found on attempt "+str(j)+": "+str(p2))
            break
    j+=1

n = p1 * p2

print("n = p1 * p2 = "+str(n))
phi_n = (p1 - 1) * (p2 - 1)#phi(n) = how many numbers below n share no factors w/ n. Given Definition of a prime, phi(any_prime_num) is always any_prime_num - 1.
print("phi_n = (p1 - 1) * (p2 - 1) = "+str(phi_n))
while True:

    e = random.randrange(10)#gens the 3rd random prime

    if e % 2 != 0:
        if phi_n % e == 0:
            k+=1
            continue
        else:
            print("Public Random Prime(is e)Found on attempt "+str(t)+": "+str(e))
            break

k = random.randrange(e)

print("num used to find d(is k): "+str(k))

d = (k * phi_n + 1)/e

print("PRIVATE key(is d): "+str(d))
#pub_key = [n, e]
#priv_key = [d, k, p1, p2, phi_n]

m = input("Type an int: ")

if gcd(int(m), n) != 1:
    quit()     #b/c m & n must not share a common factor(apparently)

c = (int(m)**e) % n    #cipher text(nums)

print("Encrypted: "+str(c))

u = (c**d) % n    #SHOULD be decrypted text(more nums)

print("Decrypted: "+str(u))
if int(m) == int(u):
    print("Successful!!")
else:
    print("Unsuccessful....")

0 个答案:

没有答案