国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python利用rsa庫做公鑰解密的方法教程

2020-02-16 11:00:37
字體:
來源:轉載
供稿:網友

前言

對于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下載。

具體的安裝方法大家可以參考這里://www.jb51.net/article/70331.htm

想了想原理,然后到rsa庫的python代碼里找了找,從verify的代碼里提取了出來,又試驗了試驗,一切OK了。

代碼如下:

#! /usr/bin/env python# -*- coding: utf-8 -*-import sys#rsafrom rsa import PublicKey, common, transform, coredef 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 2048Generating RSA private key, 2048 bit long modulus..+++..............................................+++e is 65537 (0x10001) $ openssl rsa -in pri2048.pem -out pub2048.pem -RSAPublicKey_outwriting 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.pyJust a test

一切OK,注意,公鑰pem從私鑰里析出必須用-RSAPublicKey_out,這樣pem文件的第一行和最后一行為以下,這樣rsa.PublicKey.load_pkcs1才會認識。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對武林站長站的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 祁连县| 合阳县| 塔城市| 苍梧县| 休宁县| 柘城县| 德保县| 台前县| 天门市| 册亨县| 皮山县| 牙克石市| 体育| 东光县| 江陵县| 安宁市| 保德县| 楚雄市| 开平市| 汤原县| 景东| 历史| 象山县| 麻城市| 金平| 沭阳县| 克东县| 牟定县| 湟中县| 清涧县| 安西县| 镶黄旗| 呼和浩特市| 黔西| 松潘县| 乐业县| 宁城县| 同德县| 宜兰市| 玉环县| 永德县|