【发布时间】:2015-07-14 05:17:17
【问题描述】:
java代码:
public String encrypt (String str,String key) throws EncryptException {
try{
javax.crypto.spec.SecretKeySpec keyspec = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES");
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("AES");
c.init(javax.crypto.Cipher.ENCRYPT_MODE, keyspec);
byte[] src = str.getBytes("UTF-8");
byte[] encrypt = c.doFinal(src);
return new sun.misc.BASE64Encoder().encode(encrypt).replaceAll("\r|\n", "");
}catch(Exception e){
throw new EncryptException("Encrypt failed.",e);
}
}
python 代码:
def get_enctypted(self, param_req):
BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
param_json = json.dumps(param_req)
IV = Random.new().read(AES.block_size)
cipher = AES.new(self.get_key(), AES.MODE_ECB, IV)
encrypted = cipher.encrypt(pad(param_json))
encrypted_base64 = base64.b64encode(IV + encrypted)
return encrypted_base64
当我使用相同的键和字符串运行代码时,我得到两个不同的结果,有人知道为什么吗?
【问题讨论】:
-
你能添加你正在使用的库吗?另外,我很好奇程序的不同运行之间的 IV 是否相同。你能不能多次运行python程序并检查输出是否匹配。
-
IV 在不同的运行之间是不一样的。我也尝试 IV = '\0' * AES.block_size。输出也不匹配。
标签: java python encryption aes