JAVA VERSION:
public class EncryptUtil {public static String AESEncode(String encodeRules, String content) {try {KeyGenerator keygen = KeyGenerator.getInstance("AES");keygen.init(128, new SecureRandom(encodeRules.getBytes()));SecretKey original_key = keygen.generateKey();byte[] raw = original_key.getEncoded();SecretKey key = new SecretKeySpec(raw, "AES");Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, key);byte[] byte_encode = content.getBytes("utf-8");byte[] byte_AES = cipher.doFinal(byte_encode);return new String(Base64.getEncoder().encode(byte_AES));} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}}
When i run this code:
System.out.println(EncryptUtil.AESEncode("1234567812345678", python&java"));
I've got:
V5FFUgDi7VZaJ0qGzDISoA==
PYTHON VERSION:
import base64from Crypto.Cipher import AESBLOCK_SIZE = 16 # Bytes
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
unpad = lambda s: s[:-ord(s[len(s) - 1:])]class AESUtil:__BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_sizedef __init__(self, key):self.key = keydef encrypt(self, raw):raw = pad(raw)cipher = AES.new(self.key, AES.MODE_ECB)return base64.b64encode(cipher.encrypt(raw))def decrypt(self, enc):enc = base64.b64decode(enc)cipher = AES.new(self.key, AES.MODE_ECB)return unpad(cipher.decrypt(enc))
I know java use AES/ECB/PKCS#5 by default, but when I run the encrypt
method :
cipher_text = AESUtil("1234567812345678").encryt('python&java')
got:b'3mjygpK1d7ThCRK98ssZhA=='
The pad and unpad i found them in Googles. How do I edit my PYTHON code make the cipher_text equals JAVA encryption. Can somebody know how to fix it?