700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python aes-ecb-128加解密 RSA sha256签名

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

时间:2022-06-27 10:20:06

相关推荐

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

1、下载Crypt

pip install pycrypto

下载报错,参照这篇文章处理:/weixin_42880082/article/details/126230526

2、代码

import jsonfrom Crypto.Cipher import AESimport binasciifrom Crypto.PublicKey import RSAfrom Crypto.Signature import PKCS1_v1_5from Crypto.Hash import SHA256import rsafrom Crypto.Util.Padding import padclass 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 encrypteddef 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 decrypteddef 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 reddef _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_keyif not private_key.endswith(__pem_end):private_key = private_key + __pem_endreturn private_key

3、提示未找到Crypto错误

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。