使用Python进行RSA加密

4 投票
2 回答
8372 浏览
提问于 2025-04-17 05:30

我想用Python对一个单词进行RSA加密,每次处理两个字符,并用空格填充,但我不太确定该怎么做。

比如说,如果加密指数是8,模数是37329,单词是'Pound',我该怎么做呢?我知道我需要从pow(ord('P')开始,还要考虑到这个单词有5个字符,我需要每次处理两个字符,并用空格填充。我不太确定是不是还需要在某个地方用到<<8。

谢谢!

2 个回答

1

如果你想用Python高效地编写RSA加密代码,我的GitHub仓库会帮助你理解和解释RSA的数学定义。

使用Python实现的加密算法

RSA密钥生成

def keyGen():
    ''' Generate  Keypair '''
    i_p=randint(0,20)
    i_q=randint(0,20)
    # Instead of Asking the user for the prime Number which in case is not feasible,
    # generate two numbers which is much highly secure as it chooses higher primes
    while i_p==i_q:
        continue
    primes=PrimeGen(100)
    p=primes[i_p]
    q=primes[i_q]
    #computing n=p*q as a part of the RSA Algorithm
    n=p*q
    #Computing lamda(n), the Carmichael's totient Function.
    # In this case, the totient function is the LCM(lamda(p),lamda(q))=lamda(p-1,q-1)
    # On the Contrary We can also apply the Euler's totient's Function phi(n)
    #  which sometimes may result larger than expected
    lamda_n=int(lcm(p-1,q-1))
    e=randint(1,lamda_n)
    #checking the Following : whether e and lamda(n) are co-prime
    while math.gcd(e,lamda_n)!=1:
        e=randint(1,lamda_n)
    #Determine the modular Multiplicative Inverse
    d=modinv(e,lamda_n)
    #return the Key Pairs
    # Public Key pair : (e,n), private key pair:(d,n)
    return ((e,n),(d,n))
4

这里有一个基本的例子:

>>> msg = 2495247524
>>> code = pow(msg, 65537, 5551201688147)               # encrypt
>>> code
4548920924688L

>>> plaintext = pow(code, 109182490673, 5551201688147)  # decrypt
>>> plaintext
2495247524

想了解更多关于RSA公钥加密的数学部分,可以查看这个ASPN食谱,里面有很多工具。

关于字符是如何被打包和解包成块的,以及数字是如何编码的,这些细节有点复杂。不过,这里有一个完整的、可以工作的纯Python的RSA模块

对于你特定的打包方式(每次2个字符,用空格填充),这个应该可以用:

>>> plaintext = 'Pound'    
>>> plaintext += ' '      # this will get thrown away for even lengths    
>>> for i in range(0, len(plaintext), 2):
        group = plaintext[i: i+2]
        plain_number = ord(group[0]) * 256 + ord(group[1])
        encrypted = pow(plain_number, 8, 37329)
        print group, '-->', plain_number, '-->', encrypted

Po --> 20591 --> 12139
un --> 30062 --> 2899
d  --> 25632 --> 23784

撰写回答