diff --git a/src/Commands/GenerateKeyCommand.php b/src/Commands/GenerateKeyCommand.php index 26a515c..3b6c302 100644 --- a/src/Commands/GenerateKeyCommand.php +++ b/src/Commands/GenerateKeyCommand.php @@ -5,6 +5,10 @@ use Illuminate\Console\Command; use Illuminate\Console\ConfirmableTrait; use Symfony\Component\Console\Attribute\AsCommand; +use ParagonIE\ConstantTime\{ + Base64UrlSafe, + Hex +}; #[AsCommand(name: 'ciphersweet:generate-key')] class GenerateKeyCommand extends Command @@ -18,6 +22,7 @@ class GenerateKeyCommand extends Command */ protected $signature = 'ciphersweet:generate-key {--show : Display the CipherSweet key instead of modifying files} + {--base64 : Generate key in base64 safe format} {--force : Force the operation to run when in production}'; /** @@ -58,7 +63,21 @@ public function handle() */ protected function generateRandomKey(): string { - return bin2hex(random_bytes(32)); + $randomBytes = $this->generateRandomBytes(); + + return $this->option('base64') + ? Base64UrlSafe::encode($randomBytes) + : Hex::encode($randomBytes); + } + + /** + * Generate random bytes for key + * + * @return string + */ + protected function generateRandomBytes(): string + { + return random_bytes(32); } /** diff --git a/tests/CipherSweetTest.php b/tests/CipherSweetTest.php index 838dd18..6adb155 100644 --- a/tests/CipherSweetTest.php +++ b/tests/CipherSweetTest.php @@ -115,6 +115,16 @@ User::first(); // Shouldn't throw an exception. }); +it('can generate key in hex', function(){ + $this->artisan('ciphersweet:generate-key --show') + ->assertSuccessful(); +}); + +it('can generate key in base64', function(){ + $this->artisan('ciphersweet:generate-key --show --base64') + ->assertSuccessful(); +}); + function resetCipherSweet($key) { config()->set('ciphersweet.providers.string.key', $key);