note 124806 added to function.sodium-crypto-pwhash

From: Date: Sun, 08 Mar 2020 18:08:50 +0000
Subject: note 124806 added to function.sodium-crypto-pwhash
Groups: php.notes 
Request: Send a blank email to php-notes+get-214302@lists.php.net to get a copy of this message
When encrypting, you would ideally use a randomly generated key, as that's considerably harder to guess. For example, sodium_crypto_aead_chacha20poly1305_ietf_keygen() But if you need to use a password to encrypt/decrypt, you can use sodium_crypto_pwhash(): <?php function secrets_encrypt($password, $secret) { $config = [ 'size' => SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES, 'salt' => random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES), 'limit_ops' => SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE, 'limit_mem' => SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE, 'alg' => SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, 'nonce' => random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES), ]; // $config['limit_ops'] = SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE; // $config['limit_mem'] = SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE; $key = sodium_crypto_pwhash( $config['size'], $password, $config['salt'], $config['limit_ops'], $config['limit_mem'], $config['alg'], ); $encrypted = sodium_crypto_aead_chacha20poly1305_ietf_encrypt( $secret, $config['nonce'], // Associated Data $config['nonce'], $key ); return [ 'config' => array_map('base64_encode', $config), 'encrypted' => base64_encode($encrypted), ]; } $password = 'YoxPR4QLeZ'; $secret = 'This-is-my-secret'; $data = secrets_encrypt($password, $secret); ?> To decrypt with that password, using the same limits: <?php function secrets_decrypt($password, $data) { $config = array_map('base64_decode', $data['config']); $encrypted = base64_decode($data['encrypted']); $key = sodium_crypto_pwhash( $config['size'], $password, $config['salt'], $config['limit_ops'], $config['limit_mem'], $config['alg'], ); return sodium_crypto_aead_chacha20poly1305_ietf_decrypt( $encrypted, $config['nonce'], // Associated Data $config['nonce'], $key ); } $secret = secrets_decrypt($password, $data); ?> ---- Server IP: 45.112.84.4 Probable Submitter: 185.85.3.195 (proxied: 92.237.247.170) ---- Manual Page -- http://php.net/manual/en/function.sodium-crypto-pwhash.php Edit -- https://master.php.net/note/edit/124806 Del: integrated -- https://master.php.net/note/delete/124806/integrated Del: useless -- https://master.php.net/note/delete/124806/useless Del: bad code -- https://master.php.net/note/delete/124806/bad+code Del: spam -- https://master.php.net/note/delete/124806/spam Del: non-english -- https://master.php.net/note/delete/124806/non-english Del: in docs -- https://master.php.net/note/delete/124806/in+docs Del: other reasons-- https://master.php.net/note/delete/124806 Reject -- https://master.php.net/note/reject/124806 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#214302) next »