爪哇版:
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;
}
}
当我运行此代码时:
System.out.println(EncryptUtil.AESEncode("1234567812345678", python&java"));
我有:
V5FFUgDi7VZaJ0qGzDISoA==
蟒蛇版本:
import base64
from Crypto.Cipher import AES
BLOCK_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_size
def __init__(self, key):
self.key = key
def encrypt(self, raw):
raw = pad(raw)
cipher = AES.new(self.key, AES.MODE_ECB)
return base64.b64encode(cipher.encrypt(raw))
我知道java默认使用AES/ECB/PKCS#5,但是当我运行该encrypt方法时:
cipher_text = AESUtil("1234567812345678").encryt('python&java')
得到了:b'3mjygpK1d7ThCRK98ssZhA=='
我在 Google 上找到了 pad 和 unpad。如何编辑我的 PYTHON 代码使 cipher_text 等于 JAVA 加密。有人可以知道如何修复它吗?
繁星点点滴滴
相关分类