Search code examples
phpencryptionmcryptphp-7

How do I convert an mcrypt_ecb() function to mcrypt_generic()?


In PHP 5.5 mcrypt_ecb() is depreciated. I need to convert my Cryptogrpahy class into mcrypt_generic() and mdecrypt_generic(), but the docs are have sparse details on how to use TripleDES. Any help in converting the encrypt() and decrypt() functions would be appreciated so I can prepare for the move to PHP 7.

class Crypt {
private $_key  = __CLASS__;
function __construct($key = null) {
    is_null($key)  || ($this->Key  = $key);
}

function __set($property, $value) {
    switch ($property) {
        case 'Key' : return $this->_setKey($value);
    }
}

function __get($property) {
    switch ($property) {
        case 'Key' : return $this->_key;
    }
}

public function encrypt($data) {
    $k = $this->_key;
    if (strlen($k) > 24)
        $k = substr($k, 0, 24);
    return base64_encode(base64_encode(mcrypt_ecb(MCRYPT_TripleDES, $k, $data, MCRYPT_ENCRYPT)));
}

public function decrypt($crypt) {
    $k = $this->_key;
    if (strlen($k) > 24)
        $k = substr($k, 0, 24);
    return trim(mcrypt_ecb(MCRYPT_TripleDES, $k, base64_decode(base64_decode($crypt)), MCRYPT_DECRYPT));
}

protected function _setKey($key) {
    $this->_key = (string) $key;
}
}

Solution

  • mcrypt_encrypt(MCRYPT_TripleDES, $k, $data, MCRYPT_MODE_modename)
    mcrypt_decrypt(MCRYPT_TripleDES, $k, base64_decode(base64_decode($crypt)), MCRYPT_MODE_modename)

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