Created
June 13, 2019 17:41
-
-
Save Chak10/d631c076023c62c3508f3de993ba37a0 to your computer and use it in GitHub Desktop.
Encrypt-decrypt string with Sodium
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function encrypt($message, $pass) | |
{ | |
$alg = SODIUM_CRYPTO_PWHASH_ALG_DEFAULT; | |
$opslimit = SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE; | |
$memlimit = SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE; | |
$final = $salt = openssl_random_pseudo_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES); | |
$secret_key = sodium_crypto_pwhash(SODIUM_CRYPTO_SECRETBOX_KEYBYTES, $pass, $salt, $opslimit, $memlimit, $alg); | |
$final .= hash_hmac('sha3-256', $message, $secret_key, true); | |
$final .= $nonce = openssl_random_pseudo_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); | |
$final .= sodium_crypto_secretbox($message, $nonce, $secret_key); | |
return $final; | |
} | |
function decrypt($encrypted, $pass) | |
{ | |
$alg = SODIUM_CRYPTO_PWHASH_ALG_DEFAULT; | |
$opslimit = SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE; | |
$memlimit = SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE; | |
$ls = SODIUM_CRYPTO_PWHASH_SALTBYTES; | |
$ln = SODIUM_CRYPTO_SECRETBOX_NONCEBYTES; | |
$salt = substr($encrypted, 0, $ls); | |
$secret_key = sodium_crypto_pwhash(SODIUM_CRYPTO_SECRETBOX_KEYBYTES, $pass, $salt, $opslimit, $memlimit, $alg); | |
$hmac_original = substr($encrypted, $ls, 32); | |
$nonce = substr($encrypted, $ls + 32, $ln); | |
$message = sodium_crypto_secretbox_open(substr($encrypted, $ls + 32 + $ln), $nonce, $secret_key); | |
if (!hash_equals($hmac_original, hash_hmac('sha3-256', $message, $secret_key, true))) | |
return false; | |
return $message; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment