How do you Encrypt and Decrypt a PHP String?

后端 未结 10 1545
梦毁少年i
梦毁少年i 2020-11-22 01:21

What I mean is:

Original String + Salt or Key --> Encrypted String
Encrypted String + Salt or Key --> Decrypted (Original String)

May

10条回答
  •  迷失自我
    2020-11-22 01:36

    What not to do

    WARNING:
    This answer uses ECB. ECB is not an encryption mode, it's only a building block. Using ECB as demonstrated in this answer does not actually encrypt the string securely. Do not use ECB in your code. See Scott's answer for a good solution.

    I got it on myself. Actually i found some answer on google and just modified something. The result is completely insecure however.

    ";
    echo $decrypted = decrypt($encrypted, ENCRYPTION_KEY);
    
    /**
     * Returns an encrypted & utf8-encoded
     */
    function encrypt($pure_string, $encryption_key) {
        $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $encrypted_string = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_ECB, $iv);
        return $encrypted_string;
    }
    
    /**
     * Returns decrypted original string
     */
    function decrypt($encrypted_string, $encryption_key) {
        $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypted_string = mcrypt_decrypt(MCRYPT_BLOWFISH, $encryption_key, $encrypted_string, MCRYPT_MODE_ECB, $iv);
        return $decrypted_string;
    }
    ?>
    

提交回复
热议问题