什么是php中的AES/CBC/PKCS5Padding Java



我正在尝试将Java片段下方移植到PHP,但以某种方式从PHP产生的输出与Java的输出几乎不匹配。我在做什么错?

Java摘要:

public static String generateChecksum(String requestId, String validationString) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
IvParameterSpec iv = new IvParameterSpec(new byte[16]);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
MessageDigest mDigest = MessageDigest.getInstance("SHA-512");
byte[] digestSeed = mDigest.digest(requestId.getBytes());
byte[] seedEncArray = Arrays.copyOf(digestSeed, 32);
SecretKeySpec skspec = new SecretKeySpec(seedEncArray, "AES");
cipher.init(Cipher.ENCRYPT_MODE, skspec, iv);
byte[] finalByteArray = cipher.doFinal(validationString.getBytes());
String finalValue = new String(Base64.encodeBase64(finalByteArray), "utf-8");
return finalValue;
}

Java校验和输出(虚拟数据(:

requestId:
1052
validationString:
AP_TPBabcdefghijklmnopqrstuvwxyz1234567890txnref777923212218553AP2GW_TPB2552122185536001052
finalValue:
mpCL2oS91/Mm1Xerz3rYBTEXtXFRPDodixkcJAooENvrgsc4xzrd2EeIHgmbf8rdgobmVYKFwxc0N5514FLyLyrJrxV99VztoRKBJE8LDRqXIkhU4FrobNA5FYuhVrrF

等效php片段:

$requestId = '1052';
$validationString = 'AP_TPBabcdefghijklmnopqrstuvwxyz1234567890txnref777923212218553AP2GW_TPB2552122185536001052';
$digestSeed = hash('sha512', $requestId, true);
$seedEncArray = substr($digestSeed, 0, 32);
$finalByteArray = openssl_encrypt(
    $validationString,
    'AES-128-CBC',
    $seedEncArray,
    OPENSSL_RAW_DATA,
    '0000000000000000'
);
$finalValue = base64_encode($finalByteArray);
echo 'finalByteArray: ' . $finalByteArray;
echo '<br />';
echo 'finalValue: ' . $finalValue;
echo '<br />';

php校验和输出:

finalByteArray: �V/��X�"�5���ܪ⳻����|��>��F��G�h�|�9�6��{��Y
finalValue: AvxWL4+VDliBBwgiijWlqMzcqhjis7uZPGM/h3AhB8o+0e28fOyf6z7TE4lGy9FHm2jdfAGrOcA2k7F7trlZBg==

最后,经过许多尝试,我完成了目标结果。随附的示例代码:

function encrypt($requestId, $validationString) {
    $digestSeed = hash('SHA512', $requestId, true);
    $seedEncArray = substr($digestSeed, 0, 32);
    $finalByteArray = openssl_encrypt(
        $validationString,
        'AES256',
        $seedEncArray,
        OPENSSL_RAW_DATA,
        str_repeat(chr(0), 16)
    );
    return base64_encode($finalByteArray);
}

相关内容

  • 没有找到相关文章

最新更新