Skip to content

Instantly share code, notes, and snippets.

@lucymtc
Created July 28, 2017 11:19
Show Gist options
  • Save lucymtc/54835badb5f1ac70e3e5f3d3d8fa9cf5 to your computer and use it in GitHub Desktop.
Save lucymtc/54835badb5f1ac70e3e5f3d3d8fa9cf5 to your computer and use it in GitHub Desktop.
Encrypt/decrypt passwords
<?php
/**
* Encrypt password using OpenSSL
*
* @param string $password The password to encrypt.
*/
public function encrypt_password( $password ) {
$encryption_key = base64_decode( SECURE_AUTH_KEY );
$iv = openssl_random_pseudo_bytes( openssl_cipher_iv_length( 'aes-256-cbc' ) );
$encrypted = openssl_encrypt( $password, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv );
// Append the $iv variable to use for decrypting later.
return base64_encode( $encrypted . '::' . $iv );
}
/**
* Decrypt password using OpenSSL
*
* @param string $password The password to decrypt.
*/
public function decrypt_password( $password ) {
$encryption_key = base64_decode( SECURE_AUTH_KEY );
// Grab the $iv from earlier, to decrypt.
list( $encrypted_data, $iv ) = explode( '::', base64_decode( $password ), 2 );
return openssl_decrypt( $encrypted_data, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment