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
当我使用相同的键和字符串运行代码时,我得到两个不同的结果,有人知道为什么吗?
答案 0 :(得分:2)
看看这一行 - IV = Random.new().read(AES.block_size)
。您使用random
值,因此结果当然不能相同。