前言
對于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.ythuaji.com.cn/article/89308.html
想了想原理,然后到rsa庫的python代碼里找了找,從verify的代碼里提取了出來,又試驗了試驗,一切OK了。
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#! /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驗證如下:
1
2
3
4
5
6
7
8
9
10
11
|
$ 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才會認識。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://www.cnblogs.com/Colin-Cai/p/8013009.html