Python中使用RSA加密解密

首先安装rsa包

pip install rsa

需要使用openssl生成private key

openssl genrsa -out key.pem 1024

再生成public key

openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem

然后就可以使用代码测试了

#/usr/bin/python
# -*- coding: utf-8 -*-

import rsa
from os.path import expanduser

home = expanduser("~")

with open(home+'/.ssh/key.pem', mode='rb') as privfile:
    keydata = privfile.read()
privkey = rsa.PrivateKey.load_pkcs1(keydata)

with open(home+'/.ssh/pubkey.pem', mode='rb') as pubfile:
    keydata = pubfile.read()
pubkey = rsa.PublicKey.load_pkcs1(keydata)

message = u'我是中国人'.encode('utf-8')
crypto = rsa.encrypt(message, pubkey)

icrypto = rsa.transform.bytes2int(crypto)
print(icrypto)
crypto = rsa.transform.int2bytes(icrypto)

message = rsa.decrypt(crypto, privkey)
print(message.decode('utf-8'))    

参考:

openssl generate public rsa key

rsa

RSA encryption and decryption

RSA int2bytes bytes2int


Python

这篇文章: 有用 无用
创建 2018-06-16 20:01:58 / 更新 2018-07-05 01:34:49