python利用rsa库做公钥解密的方法教程
前言
对于RSA的解密,即密文的数字的D次方求modN即可,即密文和自己做D次乘法,再对结果除以N求余数即可得到明文。D和N的组合就是私钥(privatekey)。
算法的加密和解密还是很简单的,可是公钥和私钥的生成算法却不是随意的。使用RSA公钥解密,用openssl命令就是opensslrsautl-verify-incipher_text-inkeypublic.pem-pubin-outclear_text,但其python网上还真没有找到有博文去写,只有hash的rsa解签名。
这里使用rsa库,如果没有可以到官方网址https://pypi.python.org/pypi/rsa/3.1.4下载。
具体的安装方法大家可以参考这里:https://www.nhooo.com/article/70331.htm
想了想原理,然后到rsa库的python代码里找了找,从verify的代码里提取了出来,又试验了试验,一切OK了。
代码如下:
#!/usr/bin/envpython
#-*-coding:utf-8-*-
importsys
#rsa
fromrsaimportPublicKey,common,transform,core
deff(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)
iflen(text)>0andtext[0]=='\x01':
pos=text.find('\x00')
ifpos>0:
returntext[pos+1:]
else:
returnNone
fn=sys.stdin.readline()[:-1]
public_key=sys.stdin.readline()[:-1]
x=f(open(fn).read(),open(public_key).read())
printx
用shell验证如下:
$opensslgenrsa-outpri2048.pem2048
GeneratingRSAprivatekey,2048bitlongmodulus
..+++
..............................................+++
eis65537(0x10001)
$opensslrsa-inpri2048.pem-outpub2048.pem-RSAPublicKey_out
writingRSAkey
$echo-n'Justatest'>1.txt
$opensslrsautl-sign-in1.txt-inkeypri2048.pem-out1.bin
${echo1.bin;echopub2048.pem;}|./test_rsa.py
Justatest
一切OK,注意,公钥pem从私钥里析出必须用-RSAPublicKey_out,这样pem文件的第一行和最后一行为以下,这样rsa.PublicKey.load_pkcs1才会认识。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。