Website Protection- Am i doing it right? - php

I have some doubts about my security in my website, And i was wondering if I'm doing it correctly or not.
for POST\GET requests i always use mysqli_real_escape_string($connection,$2nd_parametter);
for Password Encryption i use password_hash('$password', PASSWORD_BCRYPT, array('salt' == 9));
People told me that BCRYPT is better than SHA for Website passwords.
for Login validation i use if($username === $db_username && $password === $db_password){};
for Pages accessibility check i use
if($_SESSION['role'] == 'Admin'){header("Location: admin");}}
else{header("Location: index");}
for Database connection mysqli_connect(localhost,root,,'database');
I do realize that this connection is vulnerable since there is no
password
I would like to know if there is any better way to do these protection steps effectively and easily and even making it way stronger.

1. mysqli_real_escape_string()
The escaping function is meant to insert user input into SQL-queries, not for usage in GET/POST requests. There is a better and more comfortable way though, you can use prepared statements, to protect from SQL-injection. To escape user input for HTML, the function htmlspecialchars() is better suited.
2. password_hash()
The password_hash() function should indeed be used, though it would be safer and more future proof to write it like this:
$hashToStoreInDb = password_hash($password, PASSWORD_DEFAULT);
Your cost factor is a bit low and with PASSWORD_DEFAULT the algorithm could be changed in future should this be necessary.
3. if($username === $db_username && $password === $db_password)
This is actually not possible if you really used the password_hash() function, because of the random salt. Instead you have to check the password with:
$isPasswordCorrect = password_verify($password, $db_password);
4. if($_SESSION['role'] == 'Admin'){header("Location: admin");}}
Redirecting to protected pages is unsafe, nobody prevents an attacker to call the page directly. Each page has to check the permission on its own, if the logged in user should not see the page, then you can show the password form.

try this type
$input = "Yourpasswordtext";
$encrypted = encryptionIt( $input );
$decrypted = decryptionIt( $encrypted );
echo $encrypted . '<br />' . $decrypted;
function encryptionIt( $q ) {
$key = 'qJB0rGtIn5UB1xG03efyCp';
$encodestring = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $key ), $q, MCRYPT_MODE_CBC, md5( md5( $key ) ) ) );
return( $encodestring );
}
function decryptionIt( $q ) {
$key = 'qJB0rGtIn5UB1xG03efyCp';
$decodestring = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $key ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $key ) ) ), "\0");
return( $decodestring );
}

Related

recalling blowfish encryption w/ salt from database at login

I'm obviously new to blowfish encryption to be asking this. I believe to have one side of the equation figured out but cannot figure out how to login once the hash is in the DB. I have the following for encrypting the password on registration:
$blowfish_hash = "$2y$10$";
$salt_length = 22;
$salt = Generate_Salt($salt_length);
$hash_combined = $blowfish_hash . $salt;
$hash = crypt($password, $hash_combined);
$password = $hash;
The Generate_Salt() function is as follows:
function Generate_Salt($length) {
$unique_rndm_str = md5(uniqid(mt_rand(), true));
$base64_string = base64_encode($unique_rndm_str);
$mod_Base64_str = str_replace('+', '.', $base64_string);
$salt = substr($mod_Base64_str, 0, $length);
return $salt;
}
Once I register I get this nice long hash - great! but, when I go to login I'm unsure on how to call the hash to check against the given password: $_POST['log_password'];
Using md5 is was easy, I just encrypted this way $password = md5($password); and recalled this way $password = md5($_POST['log_password']); however reading up I realize that this is not a secure method.
I've been at this for hours, can anyone shed some light on this for me please? Any help would be appreciated.
ep
It is much easier than you think. Just use the function password_hash() instead, it will do the call to the crypt() function and handles the generation of a safe salt.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($_POST['password'], PASSWORD_DEFAULT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($_POST['password'], $existingHashFromDb);

Change password value in the database each time log in

Is it a good way to change password value each time a user log in to the database?
I have wrote a hash function to hash the password when a user register a new account on the system.
Each time the user logs in, the hash value in the database will be changed. Is it good or bad?
If you designed this hash function all by your self then... It is a very very bad idea. Why would you need something like this? If you store salted SHA-256 hashed passwords the security is good enough. You do not need to regenerate passwords, it does not provide any additional security. If lets say your app is prone to SQL-Injection, then this scheme won't protect your app. You would be a lot better if you used salted and keyed SHA-256, something like this: (I'm not a php coder, I just want our apps to be secure)
$username = 'Admin';
$password = 'gf45_gdf#4hg';
$key = 'MySuperSecretKEY!!!!';
$salt = hash('sha256', uniqid(mt_rand(), true) . 'something random' . strtolower($username));
$hash = $salt . $password . $key;
$hash = hash('sha256', $hash);
$hash = $salt . $hash;
and then checking:
$username = 'Admin';
$password = 'gf45_gdf#4hg';
$sql = '
SELECT
`hash`
FROM `users`
WHERE
`username` = "' . mysql_real_escape_string($username) . '"
LIMIT 1
;';
$r = mysql_fetch_assoc(mysql_query($sql));
$salt = substr($r['hash'], 0, 64);
$hash = $salt . $password . $key;
$hash = hash('sha256', $hash);
$hash = $salt . $hash;
if ( $hash == $r['hash'] ) {
//OK
}
So even if attacker will be able to trick the salting algorithm he does not know, a key so he won't be able to reproduce a valid hash in SQL-Injection attack.

Password hash using various methods

I was looking for the best way to store the users' passwords, but I'm not really into security, so I've found a lot of information about encryption and things like that, using Google.
I don't like using snippets that I can get in blogs or sites on the Internet, I'd rather create my own solution, so I ended up developing two functions: One to create a hash and another one to check the "hashed" password.
I don't know if I'm doing right, or if I'm just increasing my problems, so take a look at the functions below.
// Creates a simple password's hash
function hashPassword( $password = false )
{
// Checks if the password has more than 6 characters
if( strlen( $password ) < 6 )
{
// Kills the script
exit('Password is too short.');
}
// Split the 4 first characters of the password
$salt = substr( $password, 0, 4 );
// Calculate the md5 hash of the salt
$salt = md5( $salt );
// Get the rest of the password
$password = substr( $password, 3, strlen( $password ) );
// Calculate the md5 hash of the password
$password = sha1( $salt . $password );
// Crypt the password
$password = crypt( $password );
return $password;
}
That's the password that I'm going to store. Now, check out the way I'm gonna check if the password's correct.
// Checks if a hashed password match a user input password
function checkHashedPassword( $password = false, $hashedPassword = false )
{
// Checks if the password has more than 6 characters
if( strlen( $password ) < 6 )
{
// Kills the script
exit('Password is too short.');
}
// Split the 4 first characters of the password
$salt = substr( $password, 0, 4 );
// Calculate the md5 hash of the salt
$salt = md5( $salt );
// Get the rest of the password
$password = substr( $password, 3, strlen( $password ) );
// Calculate the md5 hash of the password
$password = sha1( $salt . $password );
// Checks the password and hash
if( crypt( $password, $hashedPassword ) == $hashedPassword )
{
// Returns true
return true;
}
// Returns false by default
return false;
}
As you can notice, I'm going to create a variable storing the password, and the I can check if it's ok, like the code below:
$pass = hashPassword( $_POST['password'] );
if( !checkHashedPassword( $_POST['password'], $pass ) )
{
exit('Password incorrect!');
}
So, will it work securely?
If you are looking for a general and simple way Adding simple password hashing API is still in RFC for php but have very good implementation by ircmaxwell that you can use
Example
$hash = password_hash($password, PASSWORD_BCRYPT);
Verification
if (password_verify($password, $hash)) {
/* Valid */
} else {
/* Invalid */
}
Download Here
The Password Storage Cheat Sheet from OWASP provides good guidelines for password storage and hashing.
The key points are to use a strong salt, and iterate the hash (64,000 times or more currently).
A good and widely used PHP library for password hasing is the Portable PHP Password Hashing Framework by OpenWall, I recommend checking that out.
You can use:
$pass = <query password code>;
if( $pass != hashPassword( $_POST['password'] ); )
{
exit('Password incorrect!');
}

How can I make this more secure?

I am making a login system in PHP and I was wondering if this current hash function I have is secure enough.
public function genHash( $user, $pass )
{
$user = strtoupper($user);
$staticSalt = $this->staticSalt;
$dynamicSalt = hash('SHA512', md5($user . $pass) . sha1($pass) . hash('SHA512', $user . $pass));
$final = hash('WHIRLPOOL', $pass . $dynamicSalt . $staticSalt);
return $final;
}
The static salt is just a bunch of random characters. Anyway, how can I make it more secure?
You could use different salts for each user and store them in the database but besides that this system looks pretty secure. (Not knowing the details of the server).
EDIT:
Theoretically multihashing a string increases the chance of hash collisions but I haven't found anything reliable that says this is a practical risk.

Encryption using mcrypt, PHP, and MySQL

I am trying to use mcrypt to store a password on my database. First of all, it WORKS, but only some of the time.
Here is my encryption code:
//Encryption/Decryption key
$key = $username.$username.$username.$username.$username;
//Encryption Algorithm
$cipher_alg = MCRYPT_RIJNDAEL_256;
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
$password = mcrypt_encrypt($cipher_alg, $key, $pass1, MCRYPT_MODE_CBC, $iv);
This then uploads the $username, the $iv and the $password to the MySQL database.
Here is my decryption code:
//Encryption/Decryption key
$key = $username.$username.$username.$username.$username;
//Encryption Algorithm
$cipher_alg = MCRYPT_RIJNDAEL_256;
$dbpass = mcrypt_decrypt($cipher_alg, $key, $encpass, MCRYPT_MODE_CBC, $random);
$dbpass = trim($dbpass); // Trim the fat
The $username, $iv, and $encpass(encrypted password) are retrieved from the database and the key is recreated using the username.
This WORKS but only sometimes. I can't figure out why. My only assumption is that the database can't accept some of characters the encryption produces such as quotations.
Any help would be greatly appreciated!
$salt = time(); // I would use something other than time(), something more random
// store it in the db and redirect user
connect();
$query = mysql_query("INSERT INTO user VALUES
('".mysql_real_escape_string($username)."',
'".mysql_real_escape_string(sha1($password . $salt))."',
'".mysql_real_escape_string($salt)."') ");
// returning user
$username = $_POST['username'];
$password = $_POST['password'];
// retrieve stored password
connect();
$result = mysql_query("SELECT * FROM user WHERE username = '".mysql_real_escape_string($username)."' ");
$row = mysql_fetch_assoc($result);
if (!$result) {
// user doesn't exist
}
$storedPassword = $row['password'];
$salt = $row['salt'];
$hashedPassword = sha1($password . $salt);
if ($storedPassword != $hashedPassword) {
// exit
}
else {
// redirect user
}
I'm not claiming this is the most secure, it is simply just a small example of one way hashing with a salt.
You can try below code for 2 way encryption. You may add salt with password as per your requirement.
$key = 'ecryptionkey';
$string = 'password';
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
var_dump($encrypted);
var_dump($decrypted);
I got this code from below URL and I'm using it in my application.
https://stackoverflow.com/a/9262137/1724762
If you are storing a user's password in the database, you should be using one-way hashing
Here is just a very minimalist example
$username = $_POST['username'];
$password = $_POST['password'];
$salt = 'Some Salt';
$result = mysql_query("SELECT username, password
WHERE username = '".mysql_real_escape_string($username)."'
AND password = '".mysql_real_escape_string(sha1($password . $salt))."'
LIMIT 1");
if(mysql_num_rows($result)) {
// we have a match
}
else {
// no match
}
You would have to be inserting user passwords with an appended salt using sha1 in my example. Keep in mind, this is just a suggestion for storing user passwords in the database.
Agreed that for your particular use case (storing users' passwords), a one-way hash would be best.
But for people who really do need to use mcrypt and PHP and MySQL, see the various options in MySql insert binary data to db without errors. One easy option is base64_encode/base64_decode -- here's an example.

Categories