PHP Encrypt/Decrypt with TripleDes, PKCS7, and ECB

橙三吉。 提交于 2019-12-07 01:35:23

问题


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 it returns nothing (a blank area).

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


回答1:


Thanks for anyone who took a look at my problem. I think I have solved it and here is my full solution. Hopefully it helps out someone else who is having a similar issue:

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

}

And here is the new decrypt function.

function Decrypt($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);

    $data = base64_decode($data);

    $data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');

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

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

I had to add the same code for generating the key in the correct format before I ran the mycrypt_decrypt function.



来源:https://stackoverflow.com/questions/13347528/php-encrypt-decrypt-with-tripledes-pkcs7-and-ecb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!