python rsa加密

rsa简单加密:

 1 import rsa
 2 import base64
 3 
 4 rsa_key_pair = rsa.newkeys(2048)  # 生成密钥对,返回(PublicKey(n,e), PrivateKey(n,e,d,p,q)),即(公钥对象,私钥对象)
 5 
 6 rsa_pubkey, rsa_privkey = rsa_key_pair
 7 
 8 #加密
 9 text = "hello world"
10 crypto_text_e = base64.b64encode(rsa.encrypt(text.encode("utf-8"), rsa_pubkey))
11 print("加密内容:{}".format(crypto_text_e.decode()))
12 
13 #解密
14 crypto_text_d = rsa.decrypt(base64.b64decode(crypto_text_e), rsa_privkey)
15 print("解密内容:{}".format(crypto_text_d.decode()))

base64.b64encode(),base64.b64decode() 返回类型都是bytes,打印时添加.decode()将bytes转为str.

输出:

加密内容:FSUr1akcxKaqvIR2TpDCSVlYaoXxot+shbgAKWzEbDRAAA8W5X5oRYWdo1lfgug5+KLFA/MEgn4bqgQE051C1BpMePCodvFmc3CDPRID/JrLzTUKqNItW+WATBs4DAijxdyc0M9QioL+trM1NICG7BDj+PCS6c/ZUHiDYk5qs1BtlloPXv4QHzdlrxhSHh2f+aYTnQpsY7DZpkhz37ZN9w7sjtr9hBjGdTuYD+VC1hW0s2DwYWLmy5wCarE3JjKgBFzfc9kkisDI4dcaqAvj5CDdPoy+rtyhDvIVKFY2i4yIKxK8TVDwzzuuhyn5FNNY4q8EWxsRX1YzVyEXi+IOhw==
解密内容:hello world

rsa加载密钥:

rsa.PrivateKey.load_pkcs1(证书密钥-bytes类型, 证书格式-默认为”PEM“)  # Loads a key in PKCS#1 DER or PEM format.

 

posted @ 2020-08-25 12:29  BrianSun  阅读(500)  评论(0编辑  收藏  举报