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

版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖。如要转贴,必须注明原文网址

http://www.cnblogs.com/Colin-Cai/p/8013009.html

作者:窗户

QQ:6679072

E-mail:6679072@qq.com

使用RSA公钥解密,用openssl命令就是openssl rsautl -verify -in cipher_text -inkey public.pem -pubin -out clear_text,但其python网上还真没有找到有博文去写,只有hash的rsa解签名。

想了想原理,然后到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才会认识。

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值