手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python使用RSA库做公钥解密

[日期:2017-12-10] 来源:Linux社区  作者:Colin-Cai [字体:大 中 小]

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

  这里使用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-----

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-12/149291.htm

linux
相关资讯       RSA公钥解密 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款