使用Python的RSA加密

2024-05-14 22:39:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python一次用空格填充RSA加密一个单词2个字符,但不知道该怎么做。

例如,如果加密指数是8,模数是37329,而单词是“Pound”,我该怎么做?我知道我需要从pow(ord('P')开始,并且需要考虑单词是5个字符,我需要一次填充2个字符和一个空格。我不确定,但我是否也需要在某处使用<;<;8?

谢谢你


Tags: lt指数单词rsa空格个字符poundpow
2条回答

如果您想使用python高效地编码RSA加密,我的github存储库肯定会理解和解释python中RSA的数学定义

Cryptogrphic Algoritms Implementation Using 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))

下面是一个基本示例:

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

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

请参阅ASPN cookbook recipe以获取更多用于处理RSA样式公钥加密的数学部分的工具。

字符如何打包和解包成块以及数字如何编码的细节有点神秘。这是一个完整的,有效的RSA module in pure Python

对于您的特定包装模式(一次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

相关问题 更多 >

    热门问题