Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pow()函数返回错误答案_Python_Python 3.x_Rsa_Python 3.6 - Fatal编程技术网

Python pow()函数返回错误答案

Python pow()函数返回错误答案,python,python-3.x,rsa,python-3.6,Python,Python 3.x,Rsa,Python 3.6,我正在创建一个基本的RSA加密程序,而不使用RSA库,该库接收一条秘密消息,将字符串中的每个字符转换为其ASCII值,使用公钥加密并连接这些值,然后使用私钥解密并返回字符串 所有这些都遵循着cipher=pow(普通,e,n)和plain=pow(密码,d,n)的原则。我的问题是,当我需要d和n最小为16位时,当数字变得非常大时,pow()函数似乎会导致计算错误,导致ASCII值超出转换为字符的范围。几天来,我一直在努力找出自己的错误所在。感谢您的帮助。代码如下: from random imp

我正在创建一个基本的RSA加密程序,而不使用RSA库,该库接收一条秘密消息,将字符串中的每个字符转换为其ASCII值,使用公钥加密并连接这些值,然后使用私钥解密并返回字符串

所有这些都遵循着
cipher=pow(普通,e,n)
plain=pow(密码,d,n)
的原则。我的问题是,当我需要
d
n
最小为16位时,当数字变得非常大时,
pow()
函数似乎会导致计算错误,导致ASCII值超出转换为字符的范围。几天来,我一直在努力找出自己的错误所在。感谢您的帮助。代码如下:

from random import randrange, getrandbits

def is_prime(n, k=128):
    # Test if n is not even.
    # But care, 2 is prime !
    if n == 2 or n == 3:
        return True
    if n <= 1 or n % 2 == 0:
        return False
    # find r and s
    s = 0
    r = n - 1
    while r & 1 == 0:
        s += 1
        r //= 2
    # do k tests
    for q in range(k):
        a = randrange(2, n - 1)
        x = pow(a, r, n)
        if x != 1 and x != n - 1:
            j = 1
            while j < s and x != n - 1:
                x = pow(x, 2, n)
                if x == 1:
                    return False
                j += 1
            if x != n - 1:
                return False

    return True

def generate_prime_candidate(length):
    # generate random bits
    p = getrandbits(length)
    #p = randrange(10**7,9*(10**7))
    # apply a mask to set MSB and LSB to 1
    p |= (1 << length - 1) | 1

    return p

def generate_prime_number(length=64):
    p = 4
    # keep generating while the primality test fail
    while not is_prime(p, 128):
        p = generate_prime_candidate(length)
    return p

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def generate_keypair(p, q):
    n = p * q

    #Phi is the totient of n
    phi = (p-1) * (q-1)

    #Choose an integer e such that e and phi(n) are coprime
    e = randrange(1,65537)

    g = gcd(e, phi)
    while g != 1:
        e = randrange(1,65537)
        g = gcd(e, phi)

    d = multiplicative_inverse(e, phi)
    return ((e, n), (d, n))

def multiplicative_inverse(e, phi):
    d = 0
    k = 1
    while True:
        d = (1+(k*phi))/e
        if((round(d,5)%1) == 0):
            return int(d)
        else:
            k+=1

def encrypt(m,public):
    key, n = public
    encrypted = ''
    print("Your original message is: ", m)
    result = [(ord(m[i])) for i in range(0,len(m))]
    encryption = [pow(result[i],key,n) for i in range(0,len(result))]
    for i in range(0,len(encryption)):
        encrypted = encrypted + str(encryption[i])
    #encrypted = pow(int(encrypted),key,n)
    print("Your encrypted message is: ", encrypted)
    #return result,encrypted
    return encrypted, encryption

def decrypt(e,c,private):
    key, n = private
    print("Your encrypted message is: ", c)
    print(e)
    decryption = [pow(e[i],key,n) for i in range(0,len(e))]
    print(decryption)
    result = [chr(decryption[i])for i in range(0,len(decryption)) ]
    decrypted = ''.join(result)
    print("Your decrypted message is: ",decrypted)
    return result,decrypted

def fastpow(x,y,p):
    res = 1
    x = x%p

    while(y>0):
        if((y&1) == 1):
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p
    return res



message = input("Enter your secret message: ")
p1 = generate_prime_number()
p2 = generate_prime_number()
public, private = generate_keypair(p1,p2)
print("Your public key is ", public)
print("Your private key is ", private)
encrypted,cipher = encrypt(message,public)
decrypt(cipher,encrypted,private)
从随机导入randrange,getrandbits
def是_prime(n,k=128):
#测试n是否为偶数。
#但是小心,2是最好的!
如果n==2或n==3:
返回真值
如果n>1
x=(x*x)%p
返回res
消息=输入(“输入您的秘密消息:”)
p1=生成素数()
p2=生成素数()
public,private=生成密钥对(p1,p2)
打印(“您的公钥是”,public)
打印(“您的私钥是”,private)
加密,密码=加密(消息,公共)
解密(密码、加密、专用)
回溯:

 File "<ipython-input-281-bce7c44b930c>", line 1, in <module>
   runfile('C:/Users/Mervin/Downloads/group2.py', wdir='C:/Users/Mervin/Downloads')

 File "C:\Users\Mervin\Anaconda3\lib\site-packages\spyder\util\site\sitecustomize.py", line 705, in runfile
   execfile(filename, namespace)

 File "C:\Users\Mervin\Anaconda3\lib\site-packages\spyder\util\site\sitecustomize.py", line 102, in execfile
   exec(compile(f.read(), filename, 'exec'), namespace)

 File "C:/Users/Mervin/Downloads/group2.py", line 125, in <module>
   decrypt(cipher,encrypted,private)

 File "C:/Users/Mervin/Downloads/group2.py", line 100, in decrypt
   result = [chr(decryption[i])for i in range(0,len(decryption)) ]

 File "C:/Users/Mervin/Downloads/group2.py", line 100, in <listcomp>
   result = [chr(decryption[i])for i in range(0,len(decryption)) ]

OverflowError: Python int too large to convert to C long
文件“”,第1行,在
运行文件('C:/Users/Mervin/Downloads/group2.py',wdir='C:/Users/Mervin/Downloads')
文件“C:\Users\Mervin\Anaconda3\lib\site packages\spyder\util\site\sitecustomize.py”,第705行,在runfile中
execfile(文件名、命名空间)
文件“C:\Users\Mervin\Anaconda3\lib\site packages\spyder\util\site\sitecustomize.py”,第102行,在execfile中
exec(编译(f.read(),文件名,'exec'),命名空间)
文件“C:/Users/Mervin/Downloads/group2.py”,第125行,在
解密(密码、加密、专用)
文件“C:/Users/Mervin/Downloads/group2.py”,第100行,解密
结果=[chr(解密[i]),对于范围(0,len(解密))]
文件“C:/Users/Mervin/Downloads/group2.py”,第100行,在
结果=[chr(解密[i]),对于范围(0,len(解密))]
溢出错误:Python int太大,无法转换为C long

您的方法
乘法逆
不正确。我不确定在这个方法中使用舍入法和浮点除法做了什么,但即使你把那个部分做对了,它也会太慢,需要O(φ)步。通常的计算方法是对的自适应,它以O(log(φ)2)步运行。以下是从Wikipedia文章中的psuedocode到python 3代码的简单映射:

def multiplicative_inverse(a, n):
    t, newt = 0, 1
    r, newr = n, a
    while newr:
        quotient = r // newr
        t, newt = newt, t - quotient * newt
        r, newr = newr, r - quotient * newr
    if r > 1:
        raise ZeroDivisionError("{} is not invertible".format(a))
    if t < 0:
        t = t + n
    return t
def乘法逆(a,n):
t、 牛顿=0,1
r、 newr=n,a
而newr:
商=r//newr
t、 牛顿=牛顿,t-商*newt
r、 newr=newr,r-商*newr
如果r>1:
raise ZeroDivisionError(“{}不可逆”。格式(a))
如果t<0:
t=t+n
返回t

可能相关:(您应该说明您使用的Python版本,也许2.5+解决了您的许多问题。您还应该展示一些示例输出。)欢迎使用StackOverflow。请按照您创建此帐户时的建议,阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。这里的关键词是“minimal”。你的
乘法逆()
方法是错误的。看看@DanielPryden:Incorrect当事情看起来不对劲时,有两种选择:1。“几千年来一直被人们使用的实现是错误的”或“我不理解”选择第二种,真正深入理解。