Расшифровка PHP MCrypt завершается ошибкой, если не используется AES-256

1

Я написал класс для шифрования и расшифровки строк, но я не могу использовать любой шифр, кроме MCRYPT_RIJNDAEL_256. Программа всегда сообщает, что сообщение повреждено. Как я могу это исправить?

Шифры, которые я тестировал, не выполняются MCRYPT_RIJNDAEL_128 MCRYPT_RIJNDAEL_192 MCRYPT_BLOWFISH MCRYPT_SERPENT и MCRYPT_TWOFISH.

Вот мой код:

class Crypt {
    private $masterKey;
    private $subKey;
    private $cipher = MCRYPT_RIJNDAEL_256 ;
    private $cipherMode = MCRYPT_MODE_CFB;
    //private $hashAlog = 'sha256';

    public function __construct($masterKey) {
        $this->masterKey = $masterKey;
    }

    public function setKey($masterKey) {
        $this->__construct($masterKey);
    }

    public function encrypt($message) {
        $iv = mcrypt_create_iv($this->getIVSize());
        $hmac = $this->signMsg($message);
        $this->genSubKey($iv);
        $cipherText = mcrypt_encrypt($this->cipher, $this->subKey, $message, $this->cipherMode, $iv);
        $cipherText = $iv . $hmac . $cipherText;
        return base64_encode($cipherText);
    }

    public function decrypt($enc_message) {
        $mixedMsg = base64_decode($enc_message);
        $iv = substr($mixedMsg, 0, $this->getIVSize());
        $this->genSubKey($iv);
        $hmac = substr($mixedMsg, $this->getIVSize(), strlen($this->signMsg(null)));
        $cipherText = substr($mixedMsg, $this->getIVSize() + strlen($this->signMsg(null)));
        $message = mcrypt_decrypt($this->cipher, $this->subKey, $cipherText, $this->cipherMode, $iv);
        if(!$message)
            die("Decrypt Error!");
        if($hmac != $this->signMsg($message))
            die("Message Corrupted");
        return $message;
    }

    private function genSubKey($iv) {
        $this->subKey = hash_pbkdf2("sha256", $this->masterKey, $iv, 50000, $this->getKeySize());
    }

    private function getKeySize() {
        return mcrypt_get_key_size($this->cipher, $this->cipherMode);
    }

    private function getIVSize() {
        return mcrypt_get_iv_size($this->cipher, $this->cipherMode);
    }

    private function signMsg($message) {
        return hash_hmac("sha512", $message, $this->masterKey, true);
    }
}
  • 0
    Но я ограничил длину до размера ключа, это действительно нужно?
  • 0
    Нет, вы не ограничили длину $subKey . Это вдвое длиннее, потому что hash_pbkdf2() выводит шестнадцатеричные байты по умолчанию. Вам нужно установить raw_output в true.
Показать ещё 4 комментария
Теги:
encryption
mcrypt

1 ответ

1
Лучший ответ

Проблема вызвана hash_pbkdf2 функции в genSubKey функции. Поскольку hash_pbkdf2 выводит шестнадцатеричные кодированные строки, он будет вдвое длиннее размера ключа. Чтобы решить эту проблему, нам нужно передать true в качестве дополнительного параметра к ней, позволить ей выводить необработанные байты и соответствовать размеру ключа.

Здесь скорректированный код:

private function genSubKey($iv) {
    $this->subKey = hash_pbkdf2("sha256", $this->masterKey, $iv, 50000, $this->getKeySize(), true);
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню