如何将java AES/CBC/PKCS 5 Padding转换为php

polkgigr  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(207)

我正在尝试将java脚本转换为php,但是我遇到了困难,有人能帮助我吗

String key = "mykey123823196ext470329981320tst";
String str = "Emma";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] IV = new byte[16];
    
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV);
        
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        
String result = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
        
System.out.println(result); // OUTPUT: wuN9UzYYdmevVxgTxcYIbw==

这是我尝试过的,但结果与java代码的输出不同。

$str = 'Emma';
$key = 'mykey123823196ext470329981320tst';
$iv  = '0000000000000000';
$encodedEncryptedData = base64_encode(openssl_encrypt($str, "AES-128-CBC", $key, OPENSSL_RAW_DATA, $iv));
echo $encodedEncryptedData; // OUTPUT: Vn5U9IbbxtQWxyeiLKBu9A==
w8f9ii69

w8f9ii691#

我终于找到了解决方案,基于@ MichaelFehr和@Topaco的建议,谢谢大家,下面是对我有效的代码

$str = 'Emma';
$key = 'mykey123823196ext470329981320tst';
$iv  = str_repeat(chr(0), 16);
$encodedEncryptedData = base64_encode(openssl_encrypt($str, "AES-256-CBC", $key, OPENSSL_RAW_DATA, $iv));
echo $encodedEncryptedData; // OUTPUT: wuN9UzYYdmevVxgTxcYIbw==

相关问题