ewom2468
ewom2468

Reputation: 841

Triple DES Encryption of String To 8 byte hex

I have to encrypt a string to an 8 byte hex using TDES. Below are the values (modified for reference)

key = 636948778095358323114731
pin=1234

Code for encryption :

function encryptText_3des($plainText, $key) {
  $key = hash("md5", $key, TRUE); 
  for ($x=0;$x<8;$x++) {
      $key = $key.substr($key, $x, 1);
  }
  $padded = pkcs5_pad($plainText,mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC));
  $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC));
  return $encrypted;
}

function pkcs5_pad ($text, $blocksize) {
  $pad = $blocksize - (strlen($text) % $blocksize);
  return $text . str_repeat(chr($pad), $pad);
}

However when i do this :

//outputs 3des encrypted data
echo encryptText_3des($data, $encryption_key);

I get this error :

   Warning: mcrypt_encrypt(): Encryption mode requires an initialization 
vector of size 8 

How can i get the value ?..(please i also need it as a 8 byte hex..) Thanks

Upvotes: 1

Views: 785

Answers (1)

Agnius Vasiliauskas
Agnius Vasiliauskas

Reputation: 11277

You miss initialization vector for encryption function:

function encryptText_3des($plainText, $key)
{
    $key = hash("md5", $key, TRUE);
    for ($x = 0; $x < 8; $x++) {
        $key = $key . substr($key, $x, 1);
    }
    $padded = pkcs5_pad($plainText,mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC));

    // CBC initialization vector
    $iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC, $iv));

    return $encrypted;
}

Also do not forget to save $iv string somewhere (include in encrypted string for example), because IV bytes are required for TDES decryption procedure later.

See also

Upvotes: 1

Related Questions