python rsa加解密

一. Rsa加密

​ 先去改网站生成rsa公私钥 http://web.chacuo.net/netrsakeypair

import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

public_key = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXddSrqcIqW7DT8FioLigAhkzb
acDSSrrDfcd1TFnDEuQgyxDKoqmcE5pcoNkPZXJHAaf826igF9KHhRhnCeRvs7b8
By3njyseQ3cThjyq+csLHhrlL5Hhf/mVj8TBvyJSRInYHFPIojGFsVjOiIaOUxnp
Ut9uzfCY6K7qf3EOxwIDAQAB
-----END PUBLIC KEY-----
"""

text = 'abcdefg'
a = bytes(msg, encoding="utf8")
rsakey = RSA.importKey(public_key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(a))
print(cipher_text)  # b'RkuzBbP1CyAQ1YuboLBwrxqUJdCM/HfIdfJiNJTDMmmwEDxn0VxQAd+l3lu17gaRtzYxrJtQ71ftExlDasOJUAFyMTqmshnl4TNjaKDLDkQ881lEEKLZPUjIVhuqUsMreCybQkeJyJsJZxZaL8AtUBEVZMG0Qz9jRCF25IUlFzg='

二. Rsa解密

import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

decodeStr = base64.b64decode(cipher_text)  # cipher_text是上面rsa加密的内容
prikey = Cipher_pkcs1_v1_5.new(RSA.importKey(private_key))
encry_text = prikey.decrypt(decodeStr, b'rsa') 
encry_value = encry_text.decode('utf8')
print(encry_value)  # abcdefgh
posted @ 2020-05-22 09:38  maoruqiang  阅读(3534)  评论(0编辑  收藏  举报