• Home
  • Services
  • Extensions
    • OAuth2 Server + Client
    • Cardealer
    • Questionaire
    • Sitepackage
  • Blog
  • Kontakt

Secure way to receive a Secret in PHP

06/21/2023 PHP Backend

The readable secret is only stored on user side for usage in JS code, which sends the secret with a post request to the server

On server side we use a .env variable which contains the encrypted secret

The key itself will be saved in a separate file anywhere on the server. Typically in /usr/local. 

 

composer require defuse/php-encryption
vendor/bin/generate-defuse-key

 

github.com/vlucas/phpdotenv
github.com/defuse/php-encryption

 

use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
use Dotenv\Dotenv;

// Uncomment the following lines to generate a new keyfile content
// echo $newEncryptedSecret = Crypto::encrypt('your_secret_phrase', $key);
$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();

$keyContents = file_get_contents(__DIR__ . '/../crypto/keyfile');
$key = Key::loadFromAsciiSafeString($keyContents);
$secret = Crypto::decrypt($_ENV['METIS_SECRET'], $key);

// Compare the posted secret with $secret
Back