note 122003 added to intro.sodium

From: Date: Sun, 10 Dec 2017 18:26:38 +0000
Subject: note 122003 added to intro.sodium
Groups: php.notes 
Request: Send a blank email to php-notes+get-209344@lists.php.net to get a copy of this message
<?php //Simple Usage /** * Encrypt a message * * @param string $message - message to encrypt * @param string $key - encryption key * @return string */ function safeEncrypt($message, $key) { $nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); $cipher = base64_encode( $nonce. sodium_crypto_secretbox( $message, $nonce, $key ) ); sodium_memzero($message); sodium_memzero($key); return $cipher; } /** * Decrypt a message * * @param string $encrypted - message encrypted with safeEncrypt() * @param string $key - encryption key * @return string */ function safeDecrypt($encrypted, $key) { $decoded = base64_decode($encrypted); if ($decoded === false) { throw new Exception('Scream bloody murder, the encoding failed'); } if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) { throw new Exception('Scream bloody murder, the message was truncated'); } $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit'); $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); $plain = sodium_crypto_secretbox_open( $ciphertext, $nonce, $key ); if ($plain === false) { throw new Exception('the message was tampered with in transit'); } sodium_memzero($ciphertext); sodium_memzero($key); return $plain; } //Encrypt & Decrypt your message $key = sodium_crypto_secretbox_keygen(); $enc = safeEncrypt('Abdul Rafay Hingoro', $key); //generates random encrypted string (Base64 related) echo $enc; echo '<br>'; $dec = safeDecrypt($enc, $key); //decrypts encoded string generated via safeEncrypt function echo $dec; ?> //Output DEx9ATXEg/eRq8GWD3NT5BatB3m31WEDEYLK2V4L0Am5GZGoa2rvYWUpoUeCrm7W/pdgLJrNoE6AA8U= Abdul Rafay Hingoro ---- Server IP: 208.43.231.9 Probable Submitter: 101.53.242.134 ---- Manual Page -- http://php.net/manual/en/intro.sodium.php Edit -- https://master.php.net/note/edit/122003 Del: integrated -- https://master.php.net/note/delete/122003/integrated Del: useless -- https://master.php.net/note/delete/122003/useless Del: bad code -- https://master.php.net/note/delete/122003/bad+code Del: spam -- https://master.php.net/note/delete/122003/spam Del: non-english -- https://master.php.net/note/delete/122003/non-english Del: in docs -- https://master.php.net/note/delete/122003/in+docs Del: other reasons-- https://master.php.net/note/delete/122003 Reject -- https://master.php.net/note/reject/122003 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#209344) next »