PHP code example of dwgebler / encryption

1. Go to this page and download the library: Download dwgebler/encryption 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/ */

    

dwgebler / encryption example snippets


use Gebler\Encryption\Encryption;

$crypt = new Encryption();

$crypt->passwords();   // PasswordHasher
$crypt->symmetric();   // SymmetricCrypto
$crypt->asymmetric();  // AsymmetricCrypto
$crypt->signing();     // Signing
$crypt->mac();         // Mac

$pw = $crypt->passwords();

$hash = $pw->hash('correct horse battery staple');
// Store $hash in your database.

if ($pw->verify($userInput, $hash)) {
    // login succeeded
    if ($pw->needsRehash($hash)) {
        $hash = $pw->hash($userInput);
        // update stored hash
    }
}

use Gebler\Encryption\PasswordHasher;

$pw = new PasswordHasher(
    PasswordHasher::OPSLIMIT_SENSITIVE,
    PasswordHasher::MEMLIMIT_SENSITIVE,
);

$sym = $crypt->symmetric();

$ciphertext = $sym->encryptWithPassword('secret message', 'a strong password');
$plaintext  = $sym->decryptWithPassword($ciphertext, 'a strong password');

use Gebler\Encryption\Encoding;

$sym = $crypt->symmetric();

$key = $sym->generateKey();              // 32 raw bytes
$keyHex = Encoding::toHex($key);         // store this

// later:
$key = Encoding::fromHex($keyHex);
$ciphertext = $sym->encryptWithKey('secret', $key);
$plaintext  = $sym->decryptWithKey($ciphertext, $key);

$asym = $crypt->asymmetric();
$alice = $asym->generateKeypair();
$bob   = $asym->generateKeypair();

$ciphertext = $asym->encryptAuthenticated(
    'Hi Bob, it is Alice.',
    $bob->publicKey,
    $alice->privateKey,
);

$plaintext = $asym->decryptAuthenticated(
    $ciphertext,
    $bob->privateKey,
    $alice->publicKey,
);

$ciphertext = $asym->encryptAnonymous('Anonymous tip.', $bob->publicKey);
$plaintext  = $asym->decryptAnonymous($ciphertext, $bob);

$signing = $crypt->signing();
$alice = $signing->generateKeypair();

$signed = $signing->signAttached('a public statement', $alice->privateKey);
$original = $signing->openAttached($signed, $alice->publicKey);

$signature = $signing->signDetached('a public statement', $alice->privateKey);
$valid = $signing->verifyDetached($signature, 'a public statement', $alice->publicKey);

$mac = $crypt->mac();
$key = $mac->generateKey();

$tag = $mac->sign('a message', $key);
$ok  = $mac->verify($tag, 'a message', $key); // true