2

我正在尝试将以下 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==
4

1 回答 1

0

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

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);
}
于 2019-08-02T11:41:30.517 回答