Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
发布时间:2020-09-15 16:08:34
来源:脚本之家
阅读:125
作者:mrr
Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签,具体代码如下所示:
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import rsa
import json
import hashlib
import base64
from Crypto.Cipher import AES
from ..settings_manager import settings
class RSAEncrypter(object):
"""RSA加密解密
参考 https://stuvel.eu/python-rsa-doc/index.html
对应JavaScript版本参考 https://github.com/travist/jsencrypt
[description]
"""
@classmethod
def encrypt(cls, plaintext, keydata):
#明文编码格式
content = plaintext.encode('utf8')
if os.path.isfile(keydata):
with open(keydata) as publicfile:
keydata = publicfile.read()
pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(keydata)
#公钥加密
crypto = rsa.encrypt(content, pubkey)
return base64.b64encode(crypto).decode('utf8')
@classmethod
def decrypt(cls, ciphertext, keydata):
if os.path.isfile(keydata):
with open(keydata) as privatefile:
keydata = privatefile.read()
try:
ciphertext = base64.b64decode(ciphertext)
privkey = rsa.PrivateKey.load_pkcs1(keydata, format='PEM')
con = rsa.decrypt(ciphertext, privkey)
return con.decode('utf8')
except Exception as e:
pass
return False
@classmethod
def signing(cls, message, privkey):
""" 签名
https://legrandin.github.io/pycryptodome/Doc/3.2/Crypto.Signature.pkcs1_15-module.html
"""
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
if os.path.isfile(privkey):
with open(privkey) as privatefile:
privkey = privatefile.read()
try:
key = RSA.import_key(privkey)
h = SHA256.new(message.encode('utf8'))
sign = pkcs1_15.new(key).sign(h)
sign = base64.b64encode(sign).decode('utf8')
return sign
except Exception as e:
raise e
@classmethod
def verify(cls, message, sig