How to encrypt/decrypt data in php?

前端 未结 6 915
北恋
北恋 2020-11-22 07:17

I\'m currently a student and I\'m studying PHP, I\'m trying to make a simple encrypt/decrypt of data in PHP. I made some online research and some of them were quite confusin

6条回答
  •  Happy的楠姐
    2020-11-22 07:38

    It took me quite a while to figure out, how to not get a false when using openssl_decrypt() and get encrypt and decrypt working.

        // cryptographic key of a binary string 16 bytes long (because AES-128 has a key size of 16 bytes)
        $encryption_key = '58adf8c78efef9570c447295008e2e6e'; // example
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = openssl_encrypt($plaintext, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
        $encrypted = $encrypted . ':' . base64_encode($iv);
    
        // decrypt to get again $plaintext
        $parts = explode(':', $encrypted);
        $decrypted = openssl_decrypt($parts[0], 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, base64_decode($parts[1])); 
    

    If you want to pass the encrypted string via a URL, you need to urlencode the string:

        $encrypted = urlencode($encrypted);
    

    To better understand what is going on, read:

    • http://blog.turret.io/the-missing-php-aes-encryption-example/
    • http://thefsb.tumblr.com/post/110749271235/using-opensslendecrypt-in-php-

    To generate 16 bytes long keys you can use:

        $bytes = openssl_random_pseudo_bytes(16);
        $hex = bin2hex($bytes);
    

    To see error messages of openssl you can use: echo openssl_error_string();

    Hope that helps.

提交回复
热议问题