Use libsodium to encrypt data, stored in jwt tokens

This commit is contained in:
ErickSkrauch
2019-12-05 19:37:46 +03:00
parent c3ffb08c4a
commit 642db2e045
5 changed files with 27 additions and 8 deletions

View File

@ -4,7 +4,6 @@ declare(strict_types=1);
namespace api\components\Tokens;
use Carbon\Carbon;
use Defuse\Crypto\Crypto;
use Exception;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
@ -92,8 +91,27 @@ class Component extends BaseComponent {
}
}
public function encryptValue(string $rawValue): string {
/** @noinspection PhpUnhandledExceptionInspection */
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = base64_encode($nonce . sodium_crypto_secretbox($rawValue, $nonce, $this->encryptionKey));
sodium_memzero($rawValue);
return $cipher;
}
public function decryptValue(string $encryptedValue): string {
return Crypto::decryptWithPassword($encryptedValue, $this->encryptionKey);
$decoded = base64_decode($encryptedValue);
Assert::true($decoded !== false, 'passed value has an invalid base64 encoding');
Assert::true(mb_strlen($decoded, '8bit') >= (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES));
$nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$cipherText = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$rawValue = sodium_crypto_secretbox_open($cipherText, $nonce, $this->encryptionKey);
Assert::true($rawValue !== false);
sodium_memzero($cipherText);
return $rawValue;
}
private function getAlgorithmManager(): AlgorithmsManager {
@ -113,7 +131,7 @@ class Component extends BaseComponent {
private function prepareValue($value) {
if ($value instanceof EncryptedValue) {
return Crypto::encryptWithPassword($value->getValue(), $this->encryptionKey);
return $this->encryptValue($value->getValue());
}
return $value;