繁体   English   中英

无法使用 Java 解密使用 PHP 加密的文件

[英]Unable to decrypt a file using Java that was encrypted using PHP

我的客户使用以下 PHP 代码片段加密了一个文件

$key="c5ff6db1e2f1d27d294047b220516312da1b4ba899035692e893e16815fc1234";

$content = file_get_contents(filename);
$ivlen = openssl_cipher_iv_length($cipher="AES-256-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);

$cipherText_raw = openssl_encrypt($this->plaintext, $cipher, 
                         $key, $options=OPENSSL_RAW_DATA, $iv);

$encode = base64_encode( $iv.$cipherText_raw );//Append IV and encode

我正在尝试使用带有此代码的 Java 进行解密

String hexString = "c5ff6db1e2f1d27d294047b220516312da1b4ba899035692e893e16815fc1234";

//Using Bouncycastle (org.bouncycastle.util.encoders.Hex) for Hex to byte
SecretKeySpec secretKey=new SecretKeySpec(Hex.decode(hexString),"AES");

String content = Files.readString(Paths.get("abc.xml"), StandardCharsets.UTF_8);

byte[] arrDecode  = Base64.getDecoder().decode(content);
//Extract IV
byte[] arrIV = Arrays.copyOfRange(arrDecode,0,16);
//Extract Encrypted Content
byte[] arrEnc = Arrays.copyOfRange(arrDecode,16,arrDecode.length);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(arrIV));
byte[]  xx = cipher.doFinal(arrEnc);

解密不起作用。 我收到以下错误

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

如果我使用 cipher.update(arrEnc) 我会收到大量垃圾字符。

我确定我错过了一些东西。 无法弄清楚。 我也尝试过具有相同结果的 Bouncycastle - Cipher.getInstance("AES/CBC/PKCS7Padding", "BCFIPS");

正如@topaco 出色地指出的那样,PHP 隐含地缩短了密钥。

代替

//Using Bouncycastle (org.bouncycastle.util.encoders.Hex) for Hex to byte
SecretKeySpec secretKey=new SecretKeySpec(Hex.decode(hexString),"AES");

SecretKeySpec secretKey = new SecretKeySpec(key.substring(0,32).getBytes(), "AES");

像魅力一样工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM