首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python的RSA加密

使用Python的RSA加密
EN

Stack Overflow用户
提问于 2011-11-03 01:21:30
回答 2查看 6.9K关注 0票数 4

我尝试使用Python对一个单词进行RSA加密,每次加密2个字符,并填充一个空格,但我不确定该如何进行。

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

谢谢

EN

回答 2

Stack Overflow用户

发布于 2011-11-03 01:26:25

下面是一个基本的例子:

代码语言:javascript
复制
>>> msg = 2495247524
>>> code = pow(msg, 65537, 5551201688147)               # encrypt
>>> code
4548920924688L

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

有关使用RSA式公钥加密的数学部分的更多工具,请参阅ASPN cookbook recipe

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

对于特定的打包模式(一次2个字符,用空格填充),这应该是可行的:

代码语言:javascript
复制
>>> 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
票数 4
EN

Stack Overflow用户

发布于 2017-06-08 14:32:31

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

Cryptogrphic Algoritms Implementation Using Python

RSA密钥生成

代码语言:javascript
复制
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))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7984613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档