Ignazio
Ignazio

Reputation: 1

OpenSSL [des-ede3-cbc] encrypt php IV

I need to encrypt with PHP the data to send to a company. They say I have to use my key and this IV:

{(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x01, (byte) 0x02}

They work in Java and sent me this snippet:

private static final IvParameterSpec iv = new IvParameterSpec (new byte []
{(byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, (byte) 0x05, (byte) 0x06, (byte) 0x01, (byte) 0x02});

How can I turn it into PHP? I tried like this: $iv = pack("nvc*", 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x01, 0x02); and I get the following error: Warning: openssl_encrypt (): IV passed is 10 bytes long which is longer than the 8 expected by selected cipher, truncating, if instead I put "H *" as a parameter it tells me that there are 7 unused arguments. How can I transform it? Thanks

Upvotes: 0

Views: 1224

Answers (1)

Michael Fehr
Michael Fehr

Reputation: 6414

Simply use the hex2bin-function for a hexstring conversion to binary data.

Below you find a full encryption-decryption example with your algorithm "DES-EDE3-CBC".

This is the result:

OpenSSL [des-ede3-cbc] encrypt php IV
decrypted: The quick brown fox jumps over the lazy dog

Security warning: the program has no exception handling and is for educational purpose only.

code:

<?php
echo 'OpenSSL [des-ede3-cbc] encrypt php IV' . PHP_EOL;
$plaintext = "The quick brown fox jumps over the lazy dog";
$algorithm = "DES-EDE3-CBC";
$key = "123456789012345678901234";
$ivHex = hex2bin("0102030405060102");
// encryption
$encrypted = openssl_encrypt($plaintext, $algorithm, $key, OPENSSL_RAW_DATA, $ivHex);
// decryption
$decrypted = openssl_decrypt($encrypted, $algorithm, $key, OPENSSL_RAW_DATA, $ivHex);
echo 'decrypted: ' . $decrypted . PHP_EOL;
?>

Upvotes: 2

Related Questions