python - 在 python 中实现 RSA

标签 python rsa

我正在为我的类(class)尝试在 python 中实现 RSA(我是 python 的新手),我遇到的问题是我编写的代码不适用于超过 4 位数字的数字。知道为什么会这样吗?请多多指教

p =0
q=0
n=0#modules
phyPQ = 0
e = 0 #public key exponent
d = 0#private key exponent
c = ''
m = ''

def getPrimes():
    global p
    global q
    p = long(raw_input("Enter first prime p :   "))
    q = long(raw_input("Enter second prime q :  "))

def computeModules(prime1,  prime2):
    global n
    n = prime1 * prime2
    print "Modules is = "+ `n`
    return n

def computePhyPQ(prime1,  prime2):
    global phyPQ
    phyPQ = (prime1 -1) * (prime2 -1)
    print "The phyPQ is " + `phyPQ`

def computePublickeyExponent(x):
    pubKeyExponentList= []
    for i in range(1, x):
        if  x % i != 0: 
            pubKeyExponentList.append(i)
    print pubKeyExponentList
    global e
    e =  long(raw_input("Pick a public key exponent from the list above :  "))

def computePrivateKeyExponent(phyQP,  pubKeyExpo):
    flag = 1
    count = 0
    while flag == 1:
        count = count + 1
        if (count * phyQP + 1) % phyQP == 1:
            result = (count * phyQP + 1) / float(pubKeyExpo)
            if result % 1 == 0:
                global d
                d = long(result)
                print 'The private key exponent exponent is:' +  `d`
                flag = 0

def encryptMessage(exponent,  modules):
    #c= m ^e mod n
    global c
    message= long(raw_input("Enter a value to be encrypted:"))

    c = long((message ** exponent) % modules)
    print'The encrypted message is :' + `c`

def decryptMessage(modules,  privateKeyExpo, cryptedMessage):
    #m = c^d % n
    global m
    m = (cryptedMessage ** privateKeyExpo) % modules
    print 'message after decrypting is :' + `m`

def mainMethod():
    getPrimes()
    computeModules(p, q)
    computePhyPQ(p,  q)
    computePublickeyExponent(phyPQ)
    computePrivateKeyExponent(phyPQ, e)
    encryptMessage(e, n)
    decryptMessage(n, d, c)

mainMethod() 

最佳答案

您的问题很可能是在使用浮点运算时出现的:

        result = (count * phyQP + 1) / float(pubKeyExpo)

在此算法中,始终使用任意精度整数 算法很重要。

pow() 的三参数版本将在您的实现中的几个地方有用。 pow(x, y, z) 计算任意精度整数的 (x ** y) mod z

关于python - 在 python 中实现 RSA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3312364/

相关文章:

Python Xlsxwriter 图表

c# - 仅使用公钥验证签名 (C#)

python - 带有 TK 的图形用户界面 - 按钮位置和操作

python - 类方法 __instancecheck__ 不起作用

python - Wing IDE 是否有 Eclipse 个性设置?

openssl - 从整数加载 rsa 私钥并在 openssl 中转换为 PEM 格式或 RSA 结构以签署消息

python - 从 RSA key 数据 XML 中的模数和 D 获取私钥

java - Android 中使用 RSA 解密 AES key

java - 如何从 RSAPrivateKey 获取 RSAPrivateCrtKey?

python - 在python中向json添加节点