Python pycryptodome 之 RSA 加解密

pycryptodome 支持 x509 证书加解密,关于RSA 、pycryptodome此处不详记。

安装

pip install pycryptodome

加解密

在已有RSA 公钥秘钥的基础上导入证书进行加解密

# -*- coding:UTF-8 -*-

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import os


print '+++++++++++++++++++ Used PyCryptodome encrypted and decrypted code  +++++++++++++++'

# 密码
secret_code = "123456"
# 密文
session_key = "你好RSA"
print '密文:' + session_key
print '+++++++++++++++++++ encrypt +++++++++++++++'
public_path = open("public_key.pem").read()
public_key = RSA.import_key(public_path)
cipher_rsa = PKCS1_OAEP.new(public_key)

encrypt_text = cipher_rsa.encrypt(session_key)
print '加密后:' + encrypt_text

print '+++++++++++++++++++ decrypt +++++++++++++++'
private_path = open("private_key.pem").read()
private_key = RSA.import_key(private_path, passphrase=secret_code)

cipher_rsa_decrypt = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa_decrypt.decrypt(encrypt_text)
print '解密后:' +session_key

运行结果 :

+++++++++++++++++++ Used PyCryptodome encrypted and decrypted code  +++++++++++++++
/Users/ashimarzheng/Desktop/rsa
密文:你好RSA
+++++++++++++++++++ encrypt +++++++++++++++
?yP??'79?ya8?I:??44w?ڛ6?Y?k?S?????4*??????uW?????v?s?X?5?????P???,p,A??^E?
+++++++++++++++++++ decrypt +++++++++++++++
解密后:你好RSA

【参考】

pycryptodome.org

stackoverflow

你可能感兴趣的:(python)