背景:
因项目需要,需要将一个python2编写的aes加密方式改为java实现。
1.源python2实现
from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex import hashlib import urllib class aesCrypt(): def __init__(self, undealKey): key = turnMd5(undealKey) print undealKey dealKey = dealKeyAndIV(key.lower()) self.key = dealKey # self.iv = iv self.mode = AES.MODE_ECB self.BS = AES.block_size # 补位 self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS) self.unpad = lambda s: s[0:-ord(s[-1])] def encrypt(self, text): text = self.pad(text) cryptor = AES.new(self.key, self.mode) # 目前AES-128 足够目前使用 ciphertext = cryptor.encrypt(text) # 把加密后的字符串转化为16进制字符串 return b2a_hex(ciphertext) # 解密后,去掉补足的空格用strip() 去掉 def decrypt(self, text): cryptor = AES.new(self.key, self.mode) plain_text = cryptor.decrypt(a2b_hex(text)) return self.unpad(plain_text.rstrip('