python加密算法如何转成java_Python/Java AES加解密方法互转

#!/usr/bin/env python#-*- coding: utf-8 -*-

"""@File:blog_test_code.py

@E-mail:364942727@qq.com

@Time:2020/9/8 10:08 下午

@Author:Nobita

@Version:1.0

@Desciption:None"""

importbase64importrequestsfrom Crypto.Cipher importAESfrom urllib importparseclassMyHash(object):def __init__(self):""":param mode: AES加密模式"""self.mode=AES.MODE_ECBdefMy_Aes_Encrypt(self, key, msg):"""Aes 算法加密 ( MODE = AES.MODE_ECB;无VI偏移量;)

:param key: 需加密的密钥

:param msg: 需加密的字符串

:return:"""self.key=key

self.BS=len(key)

self.pad= lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) %self.BS)

Cryptor= AES.new(self.key.encode("utf8"), self.mode)

self.ciphertext= Cryptor.encrypt(bytes(self.pad(msg), encoding="utf8"))#AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,使用base64编码

bin_encrypt_result = base64.b64encode(self.ciphertext) #输出的是二进制Unicode编码

return bin_encrypt_result.decode('utf8')defMy_Aes_Decrypt(self, key, msg):"""Aes 算法解密 ( MODE = AES.MODE_ECB;无VI偏移量;)

:param key: 需解密的密钥

:param msg: 需解密的字符串

:return:"""self.key=key

self.BS=len(key)

self.unpad= lambda s: s[0:-ord(s[-1:])]

decode=base64.b64decode(msg)

Cryptor= AES.new(self.key.encode("utf8"), self.mode)

self.plain_text=Cryptor.decrypt(decode)

bin_decrypt_result= self.unpad(self.plain_text) #输出的是二进制Unicode编码

return bin_decrypt_result.decode('utf8')defMy_Aes(self, key, msg):"""Java 加/解密工具类接口

:param key: 需加密的密钥

:param msg: 需加密的字符串

:return: 加密后的字符"""

#调用本地AES_jar包接口

url = 'http://127.0.0.1:4271/aes/encrypt'payload={"psw": key,"content": msg

}

r= requests.post(url=url, data=payload)

res= r.json()['Data']returnres

helo=MyHash()if __name__ == '__main__':print('--------------------------------------Python-AES加/解密部分--------------------------------------')

Aes_Key= "WuMlCJRN8zO886dw"Aes_Encrypt_msg= "3302019999998683302019999998684221330201999999868330201999999868"res_Aes_Encrypt=helo.My_Aes_Encrypt(Aes_Key, Aes_Encrypt_msg)print('Aes加密前字符串:{},\nAes加密结果:{}'.format(Aes_Encrypt_msg, res_Aes_Encrypt))

Aes_Decrypt_msg= "hhCWnmDtU1NxQlXiE+LMiRozGLJpbu2P/2hraeHuWUQdSUtwMmwlRlPzIJqI+lbilCOe9NU3jCm6ZcelKH3eaUie36oiU4X8S94ujyhlP/qL9mKXl4oqlQo+jZzvR2DnMn45V7v3dMQ21D97sdZQvB12t9W/O2wDzBMoKKBcqIeWiJybq/MSoGBkrmOzvs1F"res_Aes_Decryot=helo.My_Aes_Decrypt(Aes_Key, Aes_Decrypt_msg)print('Aes解密前字符串:{},\nAes解密解果:{}'.format(Aes_Decrypt_msg, res_Aes_Decryot))print('--------------------------------------Java工具类-AES加/解密部分--------------------------------------')

Java_Encrypt_result=helo.My_Aes(Aes_Key, Aes_Encrypt_msg)print('Java Aes加密接口加密后的结果:{}'.format(Java_Encrypt_result))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值