Two-way encryption: I need to store passwords that can be retrieved

前端 未结 8 1151
滥情空心
滥情空心 2020-11-22 08:42

I am creating an application that will store passwords, which the user can retrieve and see. The passwords are for a hardware device, so checking against hashes are out of

相关标签:
8条回答
  • 2020-11-22 09:46
    1. The PHP function you are after is Mcrypt (http://www.php.net/manual/en/intro.mcrypt.php).

    The example from the manual is slightly edited for this example):

    <?php
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $key = "This is a very secret key";
    $pass = "PasswordHere";
    echo strlen($pass) . "\n";
    
    $crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $pass, MCRYPT_MODE_ECB, $iv);
    echo strlen($crypttext) . "\n";
    ?>
    

    You would use mcrypt_decrypt to decrypt your password.

    1. The best algorithm is rather subjective - ask 5 people, get 5 answers. Personally if the the default (Blowfish) isn't good enough for you, you probably have bigger problems!

    2. Given that it is needed by PHP to encrypt - not sure you can hide it anywhere - welcome comments on this. Standard PHP best coding practices apply of course!

    3. Given that the encryption key will be in your code anyway, not sure what you will gain, providing the rest of your application is secure.

    4. Obviously, if the encrypted password and the encryption key are stolen, then game over.

    I'd put a rider on my answer - I'm not a PHP crypto expert, but, I think what I have answered is standard practice - I welcome comments other may have.

    0 讨论(0)
  • 2020-11-22 09:48

    Use password_hash and password_verify

    <?php
    /**
     * In this case, we want to increase the default cost for BCRYPT to 12.
     * Note that we also switched to BCRYPT, which will always be 60 characters.
     */
    $options = [
        'cost' => 12,
    ];
    echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options)."\n";
    ?>
    

    And to decrypt:

    <?php
    // See the password_hash() example to see where this came from.
    $hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
    
    if (password_verify('rasmuslerdorf', $hash)) {
        echo 'Password is valid!';
    } else {
        echo 'Invalid password.';
    }
    ?>
    
    0 讨论(0)
提交回复
热议问题