Search code examples
phpcrypt

Encrypt data with PHP


I have this code:

    $token = $this->hextobin($dataEncrypt);
    $key = $this->key_192;
    $iv = $this->iv;
    $algorithm = 'xxxx';
    $mode = 'ecb'; //QUESTION!!!
    $td = mcrypt_module_open($algorithm, '', $mode, '') ;
    $iv = substr($iv, 0, mcrypt_enc_get_iv_size($td));
    $expected_key_size = mcrypt_enc_get_key_size($td);
    $key = substr($key, 0, $expected_key_size);
    mcrypt_generic_init($td, $key, $iv);
    $response = trim(mdecrypt_generic($td, $token), '');
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    $response = explode(XXXX,$response);
    return $response[0];

But reading the PHP documentation, specifically: http://php.net/manual/en/function.mcrypt-ecb.php says that thus is obsolete and recommend mcrypt_generic() and mdecrypt_generic() for replacement. My question is how to use these functions if you ask me the same way the open mode?


Solution

  • To use mcrypt_generic() is explained here:

    However, I would recommend the simpler API mcrypt:

    Example usage:

    mcrypt_encrypt(MCRYPT_3DES, "secret key", "data to encrypt", MCRYPT_MODE_ECB);
    

    I noticed you had question marks on ecb. This is the "mode" for the encryption explained here:

    http://php.net/manual/en/mcrypt.constants.php

    According to the PHP Docs:

    • MCRYPT_MODE_ECB (electronic codebook) is suitable for random data, such as encrypting other keys. Since data there is short and random, the disadvantages of ECB have a favorable negative effect.
    • MCRYPT_MODE_CBC (cipher block chaining) is especially suitable for encrypting files where the security is increased over ECB significantly.
    • MCRYPT_MODE_CFB (cipher feedback) is the best mode for encrypting byte streams where single bytes must be encrypted.
    • MCRYPT_MODE_OFB (output feedback, in 8bit) is comparable to CFB, but can be used in applications where error propagation cannot be tolerated. It's insecure (because it operates in 8bit mode) so it is not recommended to use it.
    • MCRYPT_MODE_NOFB (output feedback, in nbit) is comparable to OFB, but more secure because it operates on the block size of the algorithm.
    • MCRYPT_MODE_STREAM is an extra mode to include some stream algorithms like "WAKE" or "RC4".

    Update If your using the CBC mode, remember to set the iv like so:

    $size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
    echo mcrypt_encrypt(MCRYPT_3DES, "secret key", "data", MCRYPT_MODE_CBC, $iv);