I want to store secure user passwords in a MySQL database with PHP.
How can I make it better?
My Class:
private static $algo = '$2a';
private static $cost = '$10';
private static $pepper = 'eMI8MHpEByw/M4c9o7sN3d';
public static function generateSalt($length) {
$randomBinaryString = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
$randomEncodedString = str_replace('+', '.', base64_encode($randomBinaryString));
return substr($randomEncodedString, 0, $length);
}
public static function generateHash($password) {
if (!defined('CRYPT_BLOWFISH'))
die('The CRYPT_BLOWFISH algorithm is required (PHP 5.3).');
$password = hash_hmac('sha256', $password, self::$pepper, false);
return crypt($password, self::$algo . self::$cost . '$' . self::generateSalt(22));
}
public static function checkPassword($hash, $password) {
$salt = substr($hash, 0, 29);
$password = hash_hmac('sha256', $password, self::$pepper, false);
$new_hash = crypt($password, $salt);
return ($hash == $new_hash);
}
Either use this answer's suggestions (for PHP >= 5.5), or the following class. Thanks to martinstoeckli for pointing out the password_hash functions. I read the code over, and the only different thing in password_hash that I can see is error-checking and DEV_URANDOM usage from the OS to generate a more random salt.
class PassHash {
public static function rand_str($length) {
$chars = "0123456789./qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
//only allowed chars in the blowfish salt.
$size = strlen($chars);
$str = "";
for ($i = 0; $i < $length; $i++)
$str .= $chars[rand(0, $size - 1)]; // hello zend and C.
return $str;
}
public static function hash($input) {
return crypt($input, "$2y$13$" . self::rand_str(22));
// 2y is an exploit fix, and an improvement over 2a. Only available in 5.4.0+
}
public static function hash_weak($input) {
return crypt($input, "$2a$13$" . self::rand_str(22)); }
// legacy support, Add exception handling and fall back to <= 5.3.0
public static function compare($input, $hash) {
return (crypt($input, $hash) === $hash);
}
}
It's what I've always used. A suggestion is also PHPass. It's tried and tested.
The only downfall in this script is that I generate random numbers from rand(), and not the source from the OS, but that's easily changed.
Also, there is no real reason to be using SHA256 hashing on top of bcrypt. SHA256 is weak, and can be broken with relatively little effort3.
In addition, hashing passwords is essential practice, but for true security, run all input through at least John the Ripper's wordlist1 to remove the most common passwords and inform a user to use a different password. Wordlists are used far more effectively than any bruteforce due to terribly weak passwords.
And as a final note, do not force your users to use symbols, uppercase and numbers, force them to use a long password2.
Length is everything (no humour intended) when it comes to bruteforcing passwords. Pretty much any preset cracker will be set to not go over 12 characters unless a config is edited. If you ever see a site with a "maximum length" on passwords, make sure to never re-use a password there, because they have no security whatsoever4.
1. Arbitrary choice of cracker; pick what you find to work best
2. http://xkcd.com/936/
3. Comparatively (it's several orders of magnitude faster and is technically security through obscurity)
4. I have even seen banks do this. Having a maximum length on their passwords made me switch banks.
Related
Good day.
Using the encryption library in CodeIgniter, I can encrypt any string by using $this->encryption->encrypt('string'); and that is the easiest way to encrypt the string. However, this method is not the safest way to secure the data I think so I decided to use salt for better encryption. I read the documentation provided by Codeigniter about the Encryption Library and I don't really understand how encryption and salt really work.
Here is my code for encryption.
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class MyEncryption {
//please do not change or delete this saltKey. "5948356750394856"
private static $saltKey = "5948356750394856";
// ================
public $CI;
function __construct()
{
$this->CI =& get_instance();
$this->CI->load->library('encryption');
}
public function encryptStringWithSalt($string) {
$p = $this->CI->encryption->encrypt(
$string,
$this->encryption_config()
);
return $p;
}
public function decryptEncryptedStringWithSalt($encryptedString) {
return $this->CI->encryption->decrypt(
$encryptedString,
$this->encryption_config()
);
}
private function encryption_config(){
$key = $this->CI->config->item('encryption_key');
$hmac_key = $this->CI->encryption->hkdf(
$key,
'sha512',
MyEncryption::$saltKey,
10,
'authentication'
);
return array(
'cipher' => 'aes-128',
'mode' => 'CTR',
'key' => MyEncryption::$saltKey,
'hmac' => true,
'hmac_digest' => 'sha224',
'hmac_key' => $hmac_key
);
}
}
As we can see, I created a function that gathers the encryption configuration. Inside that function, I have called the method $this->CI->encryption->hkdf() to create hmac key as what documentation example says. For clarification, here are the parameters of hkdf() method and the provided example.
Additionally, the return keyword with array data in encryption_config() function is the 2nd parameter of encrypt() method in encryption library. I used encryption->hkdf() because of the parameter salt on it. I am new in encryption with salt in Codeigniter so I'm really struggling on how to achieve this kind of encryption. So what I've done is that the code above really works for encryption and decryption but for some reason I don't really understand why the return value is different from the normal encryption. The difference is, this encryption method $this->encryption->encrypt("some string"); returns but using the code above returns .
Though I can decrypt that symbolic character, this will not save this encrypted data to the database with the data type of varchar but instead, it will be saved as a normal character or string. Here are the data saved to database .
My questions are, I am doing correctly? if not, what is the proper way to implement this library with salt? I want the encrypted data as normal text not a symbolic character, can I achieve that goal? and lastly? is there anyway to check the string if the string is encrypted or not? Please help me. I spend days for this problem only. I watch youtube tutorial related for encryption but no luck.
Okay. after searching on the internet I found a solution without using this CI encryption Library. I achieved my goal by using this code
<?php
defined('BASEPATH') or exit('No direct script access allowed');
/**
*
*/
class SaltEncryption
{
public $CI;
function __construct()
{
$this->CI =& get_instance();
}
public function encrypt($data){
$password = "any string";
$iv = substr(sha1(mt_rand()), 0, 16);
$password = sha1($password);
$salt = sha1(mt_rand());
$saltWithPassword = hash('sha256', $password.$salt);
$encrypted = openssl_encrypt(
"$data", 'aes-256-cbc', "$saltWithPassword", null, $iv
);
$msg_encrypted_bundle = "$iv:$salt:$encrypted";
return $msg_encrypted_bundle;
}
public function decrypt($msg_encrypted_bundle){
$password = "any string";
$password = sha1($password);
$components = explode( ':', $msg_encrypted_bundle );
if (
count($components)=== 3 &&
strlen($components[0]) === 16
) {
$iv = $components[0];
$salt = hash('sha256', $password.$components[1]);
$encrypted_msg = $components[2];
$decrypted_msg = openssl_decrypt(
$encrypted_msg, 'aes-256-cbc', $salt, null, $iv
);
if ( $decrypted_msg === false )
return false;
$msg = substr( $decrypted_msg, 41 );
return $decrypted_msg;
}
return false;
}
}
In UserPassword encoder,
public function encodePassword(UserInterface $user, string $plainPassword)
{
$encoder = $this->encoderFactory->getEncoder($user);
return $encoder->encodePassword($plainPassword, $user->getSalt());
}
encoder gets the salt from user entity.
I set a static variable to the getSalt() in User entity:
public function getSalt()
{
return 'my-static-salt';
}
But when I encode:
$password = $encoder->encodePassword($user, "my-password");
$password2 = $encoder->encodePassword($user, "my-password");
$password and $password2 are different from each other as if the encodePassword() method uses a random salt.
What am I missing?
Note for Symfony > 5.4
From Symfony 6 these classes and methods are named more appropriately replacing Encode with Hash. And moved from the Security Core package to the Password Hasher package:
For example,
Symfony\Component\Security\Core\Encoder\EncoderFactory becomes
Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory, and so on.
But the substance of the answer remains the same.
The EncoderFactory is, by default, giving you an instance of the NativePasswordEncoder (unless you have the libsodium library installed, in which case it would give you a SodiumPasswordEncoder).
If you look at NativePasswordEncoder::encodePassword() you'll see this:
public function encodePassword($raw, $salt)
{
if (\strlen($raw) > self::MAX_PASSWORD_LENGTH) {
throw new BadCredentialsException('Invalid password.');
}
// Ignore $salt, the auto-generated one is always the best
$encoded = password_hash($raw, $this->algo, $this->options);
if (72 < \strlen($raw) && 0 === strpos($encoded, '$2')) {
// BCrypt encodes only the first 72 chars
throw new BadCredentialsException('Invalid password.');
}
return $encoded;
}
Notice this comment:
// Ignore $salt, the auto-generated one is always the best
If you do not pass a salt string to password_hash(), it will generate its own randomly generated salt each time you call it, and store the salt within the result of the operation (and the hashing algorithm used).
(Similarly, in SodiumPasswordEncoder you'll see that $salt is not used at all, although a similar comment does not exist).
Further reading:
New in Symfony 4.3: Native Password Encoder
password_hash() docs
https://paragonie.com/book/pecl-libsodium/read/07-password-hashing.md
So I'm trying to create a Blowfish encrypted password with a salt using a User class that I have created, which in turns extends an overall database object that uses Late Static Bindings to CRUD from my database. Anyway, I'm trying to get this darn thing to encrypt the password before I call the create() method and inset it onto my database but each time when I do put the information in the form it goes to a blank 'update.php' screen (update.php has all my isset($_POST[]) calls for all my forms) and nothing gets uploaded to my database. Here's the code so far...
Code in update.php
if (isset($_POST["createAdmin"])) {
$user = new Users();
$user->password = $user->password_encrypt($_POST['new_password']);
$user->username = $_POST['new_username'];
$user->first_name = $_POST['first_name'];
$user->last_name = $_POST['last_name'];
if($user->create()) {
$_SESSION['new_admin_message'] = $user->password;
redirect_to("../public/admin/manage_admin.php");
}
else {
$_SESSION['new_admin_message'] ="Admin didn't create successfully";
redirect_to("../public/admin/manage_admin.php");
}
}
Code in user.php (the user class)
<?php
require_once(LIB_PATH.DS.'database.php');
class Users extends DatabaseObject {
protected static $table_name="users";
protected static $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function password_encrypt($password) {
$hashed_format = "2y$10$"; // Tels PHP to use Blowfish with a "cost" of 10
$salt_length = 22; // Blowfish salts should be 22-characters or more
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
private function generate_salt($length) {
// Not 100% unique, not 100% random, but good enoguh for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid caracters for a solt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', ".", $base64_string);
//Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
There's a couple other methods in the class that aren't important for this particular problem. I'm relatively new to OOP and PHP in general so any help would be greatly appreciated. If you could leave a short description on how you fixed the problem that would be awesome too. Thanks!!
There are three things wrong with your code:
You cannot refer to a normal method from a static method. In order for your code to work you also have to make the generate_salt method static.
You use the wrong format variable ($hash_format should be $hashed_format) when concatenating the format and salt.
Your format is wrong. Look at the documentation. The blowfish format is:
$[algo]$[difficulty]$[salt]$
Your format comes out to be:
[algo]$[difficulty]$[salt]
So, change your method to something like this:
public static function password_encrypt($password) {
$format = '$2y$10$'.$this->generate_salt(22).'$';
return crypt($password, $format);
}
Another thing, which is not technically "wrong" but is not a good thing, is your salt method. You should generate your salt from a cryptographically stronger source, such as using the mcrypt extension or, if you are on *nix, even grabbing it from /urandom or /random. Creating a "random" string by calling a mish-mash of functions, and ending up with something that looks random enough, is not a good idea.
The best thing you could do is to use the password library that comes with PHP. It will handle all the password hashing for you, and will protect you from yourself. If you have PHP <5.5.0 then you should use the compatibility library.
In other words, you should change your code to this:
public static function password_encrypt($password) {
return password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
}
These days I read a lot here on SO about password hashing and data encryption. It's a real mess, I mean, deciding what the best practice is. I need a very simple class that can be reused anywhere and that provide a decent-but-not-paranoic security level for my PHP applications (I do not handle bank data). Additionally, I want to rely as much as possible on PHP standard libs. I came up with this:
class Security {
public static function hashPassword($plain) {
$salt = md5(rand(0, 1023) . '#' . time()); // Random salt
return crypt($plain, '$2a$07$' . $salt); // '$2a$07$' is the Blowfish trigger
}
public static function checkPassword($plain, $hash) {
return (crypt($plain, $hash) === $hash);
}
public static function generateIv() {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); // It's 32
return mcrypt_create_iv($iv_size, MCRYPT_RAND);
}
public static function encrypt($key, $data, $iv = null, $base64 = true) {
if (is_null($iv)) $iv = md5($key);
$ret = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, MCRYPT_MODE_CBC, $iv);
return ($base64 ? base64_encode($ret) : $ret);
}
public static function decrypt($key, $data, $iv = null, $base64 = true) {
if (is_null($iv)) $iv = md5($key);
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $base64 ? base64_decode($data) : $data, MCRYPT_MODE_CBC, $iv), "\0");
}
}
As you can see, I choose to hash passwords with crypt() using Blowfish hashing algorithm. The return value of hashPassword() is the salt + hash that then I store in the DB. I made this choice because crypt() is available on every server, provides a confortable way to check hash regardless of algorithm used (it's based on salt prefix) and, I read, bcrypt is a decent hashing method.
Then, for data encryption I used mcrypt() Rijndael 256 algorithm with CBC mode. As you can see, I can use encryption methods in two way. I can pass a IV (and generateIv() helps me to create one) that I will store in the DB along crypted data, or, if I don't, a basic IV is derived from key in both crypt and decrypt process.
What do you think about it? Am I missing something? Can I be finally relaxed about hashing and encryption in my PHP aplications?!?
You are using Rijndael 256 bit encryption, which is not AES standard. Try to use AES (MCRYPT_RIJNDAEL_128) using 256 bit keys instead.
A random IV should be kept with cipher text if the derived key is also used to encrypt other data.
You are using out of date functions, you might want to use bcrypt and SHA-256 for the IV (only use the 16 - blocksize - left most bytes) .
Note that this list may not be complete.
I cannot get an encryption class to work (it's in a seperate file in the classes folder). The code for the class is:
class SymmetricCrypt
{
// Encryption/decryption key.
private static $msSecretKey = "Hello";
// The initialisation vector.
private static $msHexaIv = "c7098adc8d6128b5d4b4f7b2fe7f7f05";
// Use the Rijndael Algorithm.
private static $msCipherAlgorithm = MCRYPT_RIJNDAEL_128;
public static function Encrypt($plainString)
{
$binary_iv = pack("H*", SymmetricCrypt::$msHexaIv);
// Encrypt source.
$binary_encrypted_string = mcrypt_encrypt(SymmetricCrypt::$msCipherAlgorithm, SymmetricCrypt::$msSecretKey, $plainString, MCRYPT_MODE_CBC, $binary_iv);
// Convert $binary_encrypted_string to hexadeciaml format.
$hexa_encrypted_string = bin2hex($binary_encrypted_string);
return $hexa_encrypted_string;
}
public static function Decrypt($encryptedString)
{
$binary_iv = pack("H*", SymmetricCrypt::$msHexaIv);
// Convert string in hexadecimal to byte array.
$binary_encrypted_string = pack("H*", $encryptedString);
// Decrypt $binary_encrypted_string,
$decrypted_string = mcrypt_decrypt(SymmetricCrypt::$msCipherAlgorithm, SymmetricCrypt::$msSecretKey, $binary_encrypted_string, MCRYPT_MODE_CBC, $binary_iv);
return $decrypted_string;
}
}
This is how I am calling the class:
require_once 'classes/symmetric_crypt.php';
$sc = new SymmetricCrypt();
$password = "password";
$ec_password = $sc->Encrypt($password);
... insert into database.
If I echo the contents of $password, then it displays "password". If I echo $ec_password, it returns nothing.
I've used it before on a different project on a different server. Could it be something server-related? Any other ideas?
Thanks,
Adrian
Works here.
Two notes:
Your initialization vectors should not be reused. Otherwise, it gets easier to find the encryption key (see WEP).
Like premiso saids, you should not stored store passwords as decryptable strings. Use salted hashes with strong hash functions (not MD5!).