Decrypt mcrypt with openssl

前端 未结 3 1940
感情败类
感情败类 2020-12-11 10:02

Since mcrypt is considered obsolete, my task is upgrading the current code to use openssl. Sounds simple, but ... after a few days of try and failure I feel like going insan

3条回答
  •  旧巷少年郎
    2020-12-11 10:45

    Slightly old, but you can solve this with a bit of work. You can tell PHP's OpenSSL that the encrypted string is not padded, and tell it to give you the raw output (So you don't have to base64 decode it, either). You can then strip nulls from the end of the resulting string if the length of the string happens to be perfectly divisible by the IV (This is a sanity check, as if the resulting string isn't divisible by the IV then it wasn't padded at all).

    Be aware, this code has two major limitations:

    1. If, at any point, you encrypted a legitimate string that ended in two or more NULL bytes then this code will not give you the same output.

    2. If the padding of the string needed only one null byte, then this code won't strip it.

    You can solve both of these if you know for a FACT that you didn't encrypt anything that ends in null bytes, you can alter the code that strips the nulls to just do a preg_replace; just make sure you anchor the regex to the end of the string so it only strips from the end.

     1) {
                    $plain = rtrim($plain, "\0");
                    trigger_error('Detected and stripped null padding. Please double-check results!');
            }
    }
    
    
    
    var_dump(
        $message,
        bin2hex($cipher),
        $plain,
        mb_strlen($message, '8bit'),
        mb_strlen($plain, '8bit'),
        $message === $plain
    );
    

    http://3v4l.org/kYAXn

    Obviously this code comes with no major disclaimer and please test it in your use case, but someone might hopefully find this useful.

提交回复
热议问题