简体   繁体   中英

What is AES/CBC/PKCS5Padding java equivalent in php?

I'm trying to port below java snippet to php but somehow the output generated from php is of no near match to that of java. What am I doing wrong?

Java snippet:

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 checksum input/output (dummy data):

requestId:
1052

validationString:
AP_TPBabcdefghijklmnopqrstuvwxyz1234567890txnref777923212218553AP2GW_TPB2552122185536001052

finalValue:
mpCL2oS91/Mm1Xerz3rYBTEXtXFRPDodixkcJAooENvrgsc4xzrd2EeIHgmbf8rdgobmVYKFwxc0N5514FLyLyrJrxV99VztoRKBJE8LDRqXIkhU4FrobNA5FYuhVrrF

Equivalent PHP snippet:

$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 checksum output:

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

Finally after many tries I accomplished the target result. Sample code attached:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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