Java 为什么AES解密会给出空结果?
使用AES在java中完成加密,并希望在Python中解密,但在Python中结果为空(无错误)。 在标记为重复之前,请参阅代码。我想检测代码中的问题 java加密代码:Java 为什么AES解密会给出空结果?,java,python,aes,Java,Python,Aes,使用AES在java中完成加密,并希望在Python中解密,但在Python中结果为空(无错误)。 在标记为重复之前,请参阅代码。我想检测代码中的问题 java加密代码: public static String encrypt(String plainText) throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128);
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代码
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");
我看到Java显式地在
返回Base64.encodeToString(messagebytes,Base64.NO_WRAP)中将字符串编码为Base 64代码>
但是我看到您再次使用pythonbyte\u array=message.encode(“UTF-8”)
编码,其中您必须解码加密的消息
# Standard Base64 Decoding
decodedBytes = base64.b64decode(encodedStr)
decodedStr = str(decodedBytes, "utf-8")
然后才解密解码的消息。java程序和python脚本之间的连接是什么?没有连接,此java代码是android代码,dend encryptrd字符串SMS和raspberry pi GSM模块接收该消息,因此您的java代码是对密文进行base64编码的,但python代码只是执行“byte_array=message.encode(“UTF-8”)”,而不是base64解码。这些都是密码吗?Java代码中可以输入python代码的示例输出是什么?@UbaidurRehmanSoomro能否详细说明python代码的用途?Python脚本的输入是什么?