PHP code example of firehed / security

1. Go to this page and download the library: Download firehed/security library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

firehed / security example snippets


$masked_string = new Firehed\Security\Secret('string to mask');

$unmasked_string = $masked_string->reveal();


$x = new Firehed\Security\Secret('asdf');
echo $x;
// <secret>

print_r($x);
// Firehed\Security\Secret Object
// (
//     [secret] => <secret>
// )

var_dump($x);
// class Firehed\Security\Secret#2 (1) {
//   public $secret =>
//   string(8) "<secret>"
// }

var_export($x);
// Firehed\Security\Secret::__set_state(array(
//    'value' => '�AZ�',
// ))

var_dump($x->reveal());
// string(4) "asdf"

try {
    doSomethingThatThrows($x);
} catch (Throwable $ex) {
    echo $ex;
}
// Stack trace:
// #0 /some/file.php(15): doSomethingThatThrows(Object(Firehed\Security\Secret))
// #1 {main}Exception: Some message in /some/file.php:9

class User
{
    function isPasswordCorrect(string $password): bool
    {
        return password_verify($password, $this->pw_hash);
    }
}
// ...

if ($user->isPasswordCorrect($_POST['password'])) { ... }

use Firehed\Security\Secret;

class User
{
    function isPasswordCorrect(Secret $password): bool
    {
        return password_verify($password->reveal(), $this->pw_hash);
    }
}
// ...
if ($user->isPasswordCorrect(new Secret($_POST['password']))) { ... }

$container = new MyDIContainer();
$container['db_username'] = getenv('DB_USER');
$container['db_password'] = new Secret(getenv('DB_PASS'));
$container['database'] = function ($c) {
    return new PDO(
        'mysql:host=127.0.0.1;db=test',
        $c['db_username'],
        $c['db_password']->reveal(),
    );
};

// Preferred: Object-oriented

$otp = new \Firehed\Security\OTP(Secret $secret);
$code = $otp->getHOTP(int $counter, int $digits = 6, string $algorithm = OTP::ALGORITHM_SHA1);

// Legacy: function-based

$code = \Firehed\Security\HOTP(Secret $key, int $counter, int $digits = 6, string $algorithm = 'sha1');

// Preferred: Object-oriented

$otp = new \Firehed\Security\OTP(Secret $secret);
$code = $otp->getTOTP(int $step = 30, int $t0 = 0, int $digits = 6, string $algorithm = OTP::ALGORITHM_SHA1);

// Legacy: function-based
$code = \Firehed\Security\TOTP(Secret $key, array $options = []): string

// The string parameter to $secret should be user-specific, and kept protected at rest.
$secret = new \Firehed\Security\Secret('some shared secret');
$otp = new \Firehed\Security\OTP($secret);
$code = $otp->getTOTP();

// Or: $code = \Firehed\Security\TOTP($secret);

return hash_equals($user_input, $code);