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庫,如果沒有可以到官方網址https://pypi.python.org/pypi/rsa/3.1.4下載。

  想了想原理,然后到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-----


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM