Python实现AES加解密和MD5加密方法
通过Python实现AES加解密和MD5加密方法
def add_to_16(self,text): #进行长度补足 while len(text) % 16 != 0: text += '\0' return text def encrypt(self,data, password): """ AES加密 :param data:需要加密的数据 :param password: 私钥 :return: """ if isinstance(password, str): password = password.encode('utf8') bs = AES.block_size pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs) cipher = AES.new(password, AES.MODE_ECB) data = cipher.encrypt(pad(data).encode('utf8')) encrypt_data = binascii.b2a_hex(data) # 输出hex # encrypt_data = base64.b64encode(data) # 取消注释,输出Base64格式 return encrypt_data.decode('utf8') def decrypt(self,decrData, password): """ AES解密 :param decrData: 加密后的数据 :param password: 私钥 :return: """ if isinstance(password, str): password = password.encode('utf8') cipher = AES.new(password, AES.MODE_ECB) plain_text = cipher.decrypt(binascii.a2b_hex(decrData)) return plain_text.decode('utf8').rstrip('\0') def md5(self, mdkey): """ MD5加密 mdkey:需要加密地key """ new_md5 = md5() # 这里必须用encode()函数对字符串进行编码,不然会报 TypeError: Unicode-objects must be encoded before hashing new_md5.update(mdkey.encode(encoding='utf-8')) # 加密 return new_md5.hexdigest()
版权声明:本文为gcs12345原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。