Skip to content

Commit

Permalink
Merge pull request #49 from gawsoftpl/main
Browse files Browse the repository at this point in the history
Add option base64 to GenerateKeyCommand for generate key in base64. T…
  • Loading branch information
freekmurze committed Aug 21, 2023
2 parents 2afe410 + 4ae2b08 commit b1c6464
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/Commands/GenerateKeyCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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}';

/**
Expand Down Expand Up @@ -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);
}

/**
Expand Down
10 changes: 10 additions & 0 deletions tests/CipherSweetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit b1c6464

Please sign in to comment.