本文摘自php中文网,作者小云云,侵删。
RSA是一种公钥密码算法,RSA的密文是对代码明文的数字的 E 次方求mod N 的结果。下面这篇文章主要给大家介绍了关于python利用rsa库做公钥解密的方法教程,文中通过示例代码介绍的非常详细,需要的朋友可以参考下,希望能帮助到大家。前言
对于RSA的解密,即密文的数字的 D 次方求mod N 即可,即密文和自己做 D 次乘法,再对结果除以 N 求余数即可得到明文。D 和 N 的组合就是私钥(private key)。
算法的加密和解密还是很简单的,可是公钥和私钥的生成算法却不是随意的。使用RSA公钥解密,用openssl命令就是openssl rsautl -verify -in cipher_text -inkey public.pem -pubin -out clear_text,但其python网上还真没有找到有博文去写,只有hash的rsa解签名。
这里使用rsa库,如果没有可以到官方网址https://pypi.python.org/pypi/rsa/3.1.4下载。
具体的安装方法大家可以参考这里:http://www.jb51.net/article/70331.htm
想了想原理,然后到rsa库的python代码里找了找,从verify的代码里提取了出来,又试验了试验,一切OK了。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import sys
from rsa import PublicKey, common, transform, core
def f(cipher, PUBLIC_KEY):
public_key = PublicKey.load_pkcs1(PUBLIC_KEY)
encrypted = transform.bytes2int(cipher)
decrypted = core.decrypt_int(encrypted, public_key.e, public_key.n)
text = transform.int2bytes(decrypted)
if len (text) > 0 and text[ 0 ] = = '\x01' :
pos = text.find( '\x00' )
if pos > 0 :
return text[pos + 1 :]
else :
return None
fn = sys.stdin.readline()[: - 1 ]
public_key = sys.stdin.readline()[: - 1 ]
x = f( open (fn).read(), open (public_key).read())
print x
|
用shell验证如下:
1 2 3 4 5 6 7 8 9 10 11 | $ openssl genrsa -out pri2048.pem 2048
Generating RSA private key, 2048 bit long modulus
..+++
..............................................+++
e is 65537 (0x10001)
$ openssl rsa - in pri2048.pem -out pub2048.pem -RSAPublicKey_out
writing RSA key
$ echo -n 'Just a test' >1.txt
$ openssl rsautl -sign - in 1.txt -inkey pri2048.pem -out 1.bin
$ { echo 1.bin; echo pub2048.pem; } | . /test_rsa .py
Just a test
|
一切OK,注意,公钥pem从私钥里析出必须用-RSAPublicKey_out,这样pem文件的第一行和最后一行为以下,这样rsa.PublicKey.load_pkcs1才会认识。
相关推荐:
Python中排列组合计算操作的实现示例
python实现二分查找与快速排序实例详解
python使用正则表达式连接符的示例代码
以上就是j详解python利用rsa库做公钥解密的方法的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
编写一个简单的 django 应用
Python怎么打开文件的路径?
总结2020年最强Python库
Python中两个斜杠是什么运算
Python单链表中如何查找和删除节点?
pycharm和Python区别是什么
Python继承的代码示例
Python32位和64位有什么区别
Python的pandas是什么?
Python axis是什么意思
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » j详解python利用rsa库做公钥解密的方法