python aes-ecb-128加解密 RSA sha256签名

1、下载Crypt

pip install pycrypto

下载报错,参照这篇文章处理:https://blog.csdn.net/weixin_42880082/article/details/126230526

2、代码

import json
from Crypto.Cipher import AES
import binascii
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
import rsa
from Crypto.Util.Padding import pad

class Test:
    def __init__(self):
        self.unpad = lambda date: date[0:-ord(date[-1])]
    
    def ecs_ecb_encrypt(self, json_string, aes_key):
        raw = pad(json_string.encode('utf-8'), AES.block_size, style='pkcs7')  # 选择pkcs7补全

        cipher = AES.new(aes_key, AES.MODE_ECB)
        encrypted = cipher.encrypt(raw)
        encrypted = binascii.b2a_hex(encrypted)
        encrypted = encrypted.decode('utf-8')

        return encrypted

    def ecs_ecb_decrypt(self, encrypted, aes_key):
        encrypted = binascii.a2b_hex(encrypted)
        cipher = AES.new(aes_key, AES.MODE_ECB)  # ECB模式
        decrypted = cipher.decrypt(encrypted).decode('utf-8')
        encrypted = self.unpad(decrypted)
        return decrypted
    
    def rsa_sign(self, content, private_key, _hash = 'SHA-256'):
        content_keys = sorted(content.keys())
        new_content = {}
        for k in sorted(content_keys):
            new_content[k] = content[k]

        new_content = json.dumps(new_content, ensure_ascii=False, separators=(',', ':')) #separators 去除生成json字符串中间隔空格

        privateKey = self._format_private_key(private_key)
        priKey = RSA.importKey(privateKey)
        # priKey = RSA.importKey(privateKey)
        # 创建用于执行PKS 加密或者解密的密码
        signature = PKCS1_v1_5.new(priKey)
        # 内容进行sha加密
        hash_val = SHA256.new(new_content.encode("utf-8"))
        re = signature.sign(hash_val)
        # 对于内容进行PKS加密,再使用base64进行编码
        result = binascii.hexlify(re)
        red = result.decode('utf-8')
        return red
    
   def _format_private_key(self, private_key):
        """对私进行格式化,缺少"-----BEGIN RSA PRIVATE KEY-----"和"-----END RSA PRIVATE KEY-----"部分需要加上

        :param private_key: 私钥
        :return: pem私钥字符串
        :rtype: str
        """
        __pem_begin = '-----BEGIN RSA PRIVATE KEY-----\n'
        __pem_end = '\n-----END RSA PRIVATE KEY-----'

        if not private_key.startswith(__pem_begin):
            private_key = __pem_begin + private_key
        if not private_key.endswith(__pem_end):
            private_key = private_key + __pem_end
        return private_key

3、提示未找到Crypto错误

        找到Python的Lib包文件夹,找到crypto文件夹,将crypto改为首字母大写Crypto

你可能感兴趣的:(python,加解密,哈希算法,算法,RSA,aes)