osama.khatib
osama.khatib

Reputation: 51

DES-encrypting a string and converting to hex

I am trying to find a way in PHP that can encrypt a string in hex using DES algorithm. The result I need should be exactly like this page.

All PHP codes that I tried gave different results than what I got in that page. I tried this code for example:

<?php
function Encrypt($data, $key)
{    
  $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
  return $encData;
}
echo strtoupper(bin2hex(Encrypt("12341234", "1100000120140129")));
?>

The result was: 0D54E1C0B08DCB90. While in this link, the result is: 4DC7D8B78F0F33A3.

Note that 31313030303030313230313430313239 is 1100000120140129 in hex and 3132333431323334 is 12341234 in hex.

Upvotes: 3

Views: 3951

Answers (2)

osama.khatib
osama.khatib

Reputation: 51

This code did the trick for me:

$keyA = "11000001";
$keyB = "20140129";
$data = "12341234";
$TMP = mcrypt_encrypt('tripledes', $keyA, $data, 'ecb');
$TMP = mcrypt_decrypt('tripledes', $keyB, $TMP, 'ecb');
echo strtoupper(bin2hex(mcrypt_encrypt('tripledes', $keyA, $TMP, 'ecb')));

I used two-key triple DES method to generate the exact result in this DES calculator website.

  1. Encrypt the data using the first half of the key (most left 8 digits)
  2. Decrypt the ciphertext using the second half of the key (most right 8 digits)
  3. Re-encrypt the ciphertext using the first half of the key again

Thanks to @Duncan for the useful help.

Upvotes: 1

Duncan Jones
Duncan Jones

Reputation: 69389

This problem seems to be caused by the way PHP reads keys and data when you supply them as strings. Solve this problem by using code such as the following:

$key = pack('H*', "0123456789abcdef"); // this correctly maps hex to bytes
$data = pack('H*', "0123456789abcdef");
echo bin2hex(mcrypt_encrypt(MCRYPT_DES, $key, $data, MCRYPT_MODE_ECB));

This outputs 56cc09e7cfdc4cef which matches the DES calculator (proof).


For those interested, I also used the following Java code to deduce what was going on. This prints the same result as the PHP:

SecretKey key = new SecretKeySpec(new byte[8], "DES");

Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);

System.out.println(DatatypeConverter.printHexBinary(cipher
    .doFinal(new byte[8])));

Upvotes: 0

Related Questions