PHP Encrypt/Decrypt with TripleDes, PKCS7, and ECB

Posted by Brandon Green on Stack Overflow See other posts from Stack Overflow or by Brandon Green
Published on 2012-11-12T16:30:36Z Indexed on 2012/11/12 17:00 UTC
Read the original article Hit count: 343

Filed under:
|
|
|
|

I've got my encryption function working properly however I cannot figure out how to get the decrypt function to give proper output.

Here is my encrypt function:

function Encrypt($data, $secret)
{    
  //Generate a key from a hash
  $key = md5(utf8_encode($secret), true);

  //Take first 8 bytes of $key and append them to the end of $key.
  $key .= substr($key, 0, 8);

  //Pad for PKCS7
  $blockSize = mcrypt_get_block_size('tripledes', 'ecb');
  $len = strlen($data);
  $pad = $blockSize - ($len % $blockSize);
  $data .= str_repeat(chr($pad), $pad);

  //Encrypt data
  $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');

  return base64_encode($encData);

}

Here is my decrypt function:

function Decrypt($data, $secret)
{
    $text = base64_decode($data);

    $data = mcrypt_decrypt('tripledes', $secret, $text, 'ecb');

    $block = mcrypt_get_block_size('tripledes', 'ecb');
    $pad   = ord($data[($len = strlen($data)) - 1]);

    return substr($data, 0, strlen($data) - $pad);
}

Right now I am using a key of test and I'm trying to encrypt 1234567. I get the base64 output from encryption I'm looking for, but when I go to decrypt I get a blank response.

I'm not very well versed in encryption/decryption so any help is much appreciated!!

© Stack Overflow or respective owner

Related posts about php

Related posts about encryption