Skip to content

Instantly share code, notes, and snippets.

@ToshY
Last active September 5, 2020 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToshY/afb437ba5f815ab1901ef3eaccef61b4 to your computer and use it in GitHub Desktop.
Save ToshY/afb437ba5f815ab1901ef3eaccef61b4 to your computer and use it in GitHub Desktop.
Simple one-way encryption in PHP
<?php
class OneWayEncryption{
/*
* One way encryption; hash + salt
*/
private const COST = '14';
private function uniqueSalt() {
return substr( strtr( base64_encode( random_bytes( 16 ) ), '+', '.' ), 0, 22 );
}
public function createHash( $string ) {
return crypt( $string, ( '$2a$' . self::COST . '$' . $this->uniqueSalt() ) );
}
public function checkPassword( $hash, $password ) {
// First 29 characters incl. algo + cost + salt
$full_salt = substr( $hash, 0, 29 );
// Hash
$new_hash = crypt( $password, $full_salt );
// Return
if( hash_equals( $hash, $new_hash ) ) return TRUE;
}
}
# Encryption
$encryptor = new OneWayEncryption();
# Create hash (and save to DB)
$salty_hash = $encryptor->createHash('mypassword123');
# Check hash
if($encryptor->checkPassword($db_password_entry, 'mypassword123')){
# Correct password: proceed with login, session creation, etc.
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment