脚本专栏 
首页 > 脚本专栏 > 浏览文章

python利用rsa库做公钥解密的方法教程

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

前言

对于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下载。

具体的安装方法大家可以参考这里:https://www.jb51.net/article/70331.htm

想了想原理,然后到rsa库的python代码里找了找,从verify的代码里提取了出来,又试验了试验,一切OK了。

代码如下:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
#rsa
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验证如下:

$ 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自动化运维之IP地址处理模块详解
下一篇:Python跨文件全局变量的实现方法示例
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网