[英]Why AES decryption giving empty result?
Encryption done in java using AES and wanted to decrypt in Python, but the result is empty in python (no errors). 加密是使用AES在Java中完成的,并且想在Python中解密,但是python中的结果为空(无错误)。 See the code before marking as duplicate.
标记为重复之前,请参见代码。 I want to detect problem in my code.
我想检测代码中的问题。
java encryption code: Java加密代码:
public static String encrypt(String plainText) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
String keyStr = Base64.encodeToString(secretKey.getEncoded(), Base64.NO_WRAP);
byte[] initVector = new byte[16];
(new Random()).nextBytes(initVector);
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] plainTextByte = plainText.getBytes();
byte[] encryptedByte = cipher.doFinal(plainTextByte);
byte[] messagebytes = new byte[initVector.length + encryptedByte.length];
System.arraycopy(initVector, 0, messagebytes, 0, 16);
System.arraycopy(encryptedByte, 0, messagebytes, 16, encryptedByte.length);
return Base64.encodeToString(messagebytes, Base64.NO_WRAP);
}
Python code Python代码
def decrypt(key, message):
"""
Input encrypted bytes, return decrypted bytes, using iv and key
"""
byte_array = message.encode("UTF-8")
iv = byte_array[0:16] # extract the 16-byte initialization vector
messagebytes = byte_array[16:] # encrypted message is the bit after the iv
cipher = AES.new(key.encode("UTF-8"), AES.MODE_CBC, iv)
decrypted_padded = cipher.decrypt(messagebytes)
decrypted = unpad(decrypted_padded)
return decrypted.decode("UTF-8");
I see that the Java is explicitly encoding the string as Base 64 at return Base64.encodeToString(messagebytes, Base64.NO_WRAP);
我看到Java在
return Base64.encodeToString(messagebytes, Base64.NO_WRAP);
将字符串显式编码为Base 64 return Base64.encodeToString(messagebytes, Base64.NO_WRAP);
But i see that you are again encoding in python byte_array = message.encode("UTF-8")
where in you will have to decode the encrypted message 但是我看到您再次使用python
byte_array = message.encode("UTF-8")
进行编码,在其中您将必须解码加密的消息
# Standard Base64 Decoding
decodedBytes = base64.b64decode(encodedStr)
decodedStr = str(decodedBytes, "utf-8")
And only then Decrypt the decoded message. 然后才解密已解码的消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.