前言
對于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下載。
具體的安裝方法大家可以參考這里:http://www.gxlcms.com/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才會認識。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com