前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python使用rsa库做公钥解密(网上别处找不到)

python使用rsa库做公钥解密(网上别处找不到)

作者头像
窗户
发布2018-02-07 16:09:39
3.3K0
发布2018-02-07 16:09:39
举报
文章被收录于专栏:窗户窗户

  使用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下载。

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

  代码如下:

代码语言:javascript
复制
#! /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验证如下:

代码语言:javascript
复制
 $ 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才会认识。

  -----BEGIN RSA PUBLIC KEY-----

  -----END RSA PUBLIC KEY-----

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档