每日一模块-Crypto模块RSA非对称加密

pycrypto模块支持的加密方式

  1. 对称加密方式:

    AES 
    DES 
    ARC4

  2. 散列值计算:

    MD5 
    SHA 
    HMAC

  3. 公钥加密和签名:

    RSA 
    DSA

RSA加密算法是一种非对称加密算法

安装

1 pip3 install pycryptodome 
2 快速方式:pip3 install -i https://pypi.douban.com/simple pycryptodome
3 PyCrypto 已死,请替换为 PyCryptodome  
4 如有异常,尝试
5 需要在python目录里面把Python36\Lib\site-packages下的crypto文件改名,没错,就是直接改成Crypto。结果就能用了...
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256

pip install pycrypto

如果导入错误则参考: 
ImportError: No module named Crypto.Cipher

 

# -*- coding: utf-8 -*-

from pprint import pprint

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64


# rsa算法生成实例
def get_key():
    rsa = RSA.generate(1024, Random.new().read)
    # master的秘钥对的生成
    private_pem = rsa.exportKey()
    public_pem = rsa.publickey().exportKey()

    return {
        "public_key": public_pem.decode(),
        "private_key": private_pem.decode()
    }


# 生成的公钥私钥对
private_key = """-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDfEQ82qUrto7h4BL3TsA/DFXSdM44cbeY4kPccD7gLGhaZRClz
YKIh5zYdfjBGF+0HXfMa1u9b7GNs2AjVIsx8Kx0QLnMfmtkmGWGhOXz/9IDLKJOx
0weKv61gysKItgzVKn2mbLool4R/PQBc3AjDyHw+io1KpVz+3kRTaGs1fQIDAQAB
AoGAWB4kFWLA/6k6OOcemd4mC9mQ7HyuOdrMJDJX+5TWDkSrArajbTmSMrRkczgj
F71h3BQn8cVQXs695ARfUNrjTbi2Y0LjN7ScK7ExzTLdoMEFw5JsHggJZ0zBQY6w
mwOdGfqzA6tZPXgkn+jqEha+CD6GrwnTM1oDGJC/aKG2OmECQQDkO9IhUhFc/PSU
0zvGE6AOcqk5wlOuvMg+oAFHJHJZ9XW7+X/Nx0ZoVDFq/cZQj+46t+fiwUwhdW7l
IfCvNGKFAkEA+jRQmWGKrbf1ns4S0SezJvysd5O6otRGJXr+Ex2uDhc39ZTeUsyg
kjrLhp8STLMOmql+8g5fghct17EuCX1EmQJBAJz9BNnEkIrst/OSpH/nyeWGOx6u
q077LaXd+2MLD9kO/O/Se3V5B9YFa4STkJCjoBMloswXd51gIGpdgSeSmd0CQQCL
PrwwcGmWfo+ynqs4PajlpK9zKQMwhYS4bTejedwZOXDKOtx0Ji+i0hfcxwCPMQOK
rZPZsIgUxUOdC508aLvZAkBDkHxunCzDm0w4DdTUN7S9YSpVvQEjK/xUQiWaKV12
8QgskhU2DNdYK2NxifnWrKtx3uQmqMxX5aLuJZ4493yr
-----END RSA PRIVATE KEY-----"""

public_key = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfEQ82qUrto7h4BL3TsA/DFXSd
M44cbeY4kPccD7gLGhaZRClzYKIh5zYdfjBGF+0HXfMa1u9b7GNs2AjVIsx8Kx0Q
LnMfmtkmGWGhOXz/9IDLKJOx0weKv61gysKItgzVKn2mbLool4R/PQBc3AjDyHw+
io1KpVz+3kRTaGs1fQIDAQAB
-----END PUBLIC KEY-----
"""


# 公钥加密
def rsa_encode(message, public_key):
    rsakey = RSA.importKey(public_key)  # 导入读取到的公钥
    cipher = PKCS1_v1_5.new(rsakey)  # 生成对象
    # 通过生成的对象加密message明文,注意,在python3中加密的数据必须是bytes类型的数据,不能是str类型的数据
    cipher_text = base64.b64encode(
        cipher.encrypt(message.encode(encoding="utf-8")))
    # 公钥每次加密的结果不一样跟对数据的padding(填充)有关
    return cipher_text.decode()


# 私钥解密
def rsa_decode(cipher_text, private_key):
    rsakey = RSA.importKey(private_key)  # 导入读取到的私钥
    cipher = PKCS1_v1_5.new(rsakey)  # 生成对象
    # 将密文解密成明文,返回的是一个bytes类型数据,需要自己转换成str
    text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
    return text.decode()


if __name__ == '__main__':
    message = "你好,世界!"
    cipher = rsa_encode(message, public_key)
    print(cipher)
    # 输出是一行,天长了,折行显示
    # vyuQHYhjYrPZK6pJMbbcjb1Q7JTLyRDPIoV7z6OkMQsuBNk0++C
    # tb3dzo0EvjUhaSOZnE9LjODgEqeTR7I459cDp8izmb970BnKj74
    # 6SBtGunK24nudW86ek0JXdYsF5T/IPaphU8d56rdjW+wZv7OfSL
    # m2HgXLXCI6NbJuJXhg=

    msg = rsa_decode(cipher, private_key)
    print(msg)
    # 你好,世界!

你可能感兴趣的:(每日一模块-Crypto模块RSA非对称加密)