Hashing Passwords



If you are creating a product that needs passwords for user authentication, you will have to put in place a system for verifying the login details of your users. However, there are major security risks related to storing unencrypted passwords in your database.

So there is a one method by which we can secure passwords of the users is Hasing Passwords. So in this chapter, we will define hashing password, discuss its importance, and show how hashing technology helps to the modern secure design of our Passwords.

Basics of Hashing Passwords

Using an encryption method, password hashing compresses all data, like your password, to a brief string of characters and/or numbers. Password hashing helps stop attackers from accessing your login information in case that a website is hacked. Instead, all they get is the unintelligible encrypted "hash" that your password created.

Hashing Passwords

The hash function md5() is widely used and generates a 32-character string from any input. Here are some examples of the way a hash looks like −

  • "secret123": 5d7845ac6ee7cfffafc5fe5f35cf666d
  • "Helloworld": a165968b0a8084a041aed89bf40d581f
  • "mypassword": 34819d7beeabb9260a5c854bc85b3e44
  • "password123": 482c811da5d5b4bc6d497ffa98491e38
  • "hashingpasswords": 6b408e41b2f7a9944367d2b535a201f8

This is a simple explaination of what we can learn from the examples −

  • Even a small, minor change to the input can completely change the hash function's result. For example, changing a single character can change the look of the output completely.
  • Whatever the length of the input, the hash function always produces an output of the same length. It is always the same size-32 characters.
  • If you use the same input and hash function, you will constantly get the same result. This is important because it shows how consistent and reliable the process is.
  • Knowing the hash function only makes it very difficult to determine the original input (e.g. as a password) from the output only. It is usually faster to try to guess the original input by looking at a large number of possibilities than to try to figure it out directly.

How password hashing works?

Let us see the practical process of password hashing −

Hashing Passwords table
  • A user creates a username and password by browsing a website and filling out a form.
  • A hash function is applied to the password, and the result is stored in the database.
  • The user reenters his/her password on the website after logging in.
  • The same hashing function that was used before is applied to the password that was entered.
  • The server verifies this hash to the one that is kept in the database for the user.
  • The user is given access if there is an exact match between the two hashes.
Hashing Passwords - Hashed Table

Security of Hashing Passwords

Given that hashes are the same length regardless of password, you can feel inclined to use a short, memorable password. In reality, you should do the reverse. The password you choose is crucial for protecting your data.

Once a cybercriminal takes over password hashes from a website, the actual password hacking process starts. This operation happens offline, on the cybercriminal's PC. Cybercriminals use a hashing function to generate hashes that match yours.

Because the functions are publicly known, password hackers can just calculate hashes for regularly used words and combinations. Then they compare the cracked passwords to these dictionaries.

These dictionaries contain much more than just words. Prefixes, suffixes, the convention of substituting letters for numerals (e.g., using 1 instead of l), and many other things are among them. This means that weak passwords can be easily broken.

To Ensure Strong Password Security

To make sure strong password security here are some important tips you need to follow −

  • Create passwords that are long and include a combination of uppercase and lowercase letters, numbers, and special characters.
  • Use different passwords for each of your accounts.
  • Do not use easily accessible personal information like your name, birthdate, or common words.
  • Whenever possible, enable two-factor authentication for your accounts.
  • Change your passwords time to time, mainly for sensitive accounts like email and banking.
  • Avoid storing passwords in easily accessible places like plain text files or sticky notes.
  • Ensure that your devices and software are up to date with the latest security patches to protect against known vulnerabilities that could be exploited by attackers.

Password Storage Methods

There are several methods for storing passwords securely −

  • Hashing − Hashing means converting a password into a fixed-length string of characters with a mathematical method. The hashed password is then saved in a database. A user's password is hashed once again and compared to the hash that is stored when they log in. The hashing algorithms MD5, SHA-1, and SHA-256 are commonly used.
  • Salted Hashing − For each password, a unique random value-referred to as a salt-is added before hashing. By using distinct salts, this ensures that two users with the same password will have different hashed values. Rainbow table attacks, in which attackers precompute hashes for popular passwords, are prevented by salted hashing.
  • Key Derivation Functions (KDFs) − The purpose of KDFs is to securely extract cryptographic keys from passwords. To slow down brute-force attacks, they often use features like salting and iteration counts. PBKDF2 (Password-Based Key Derivation Function 2) and bcrypt are two examples of KDFs.
  • Key Stretching − It is the practice of repeatedly iterating the hashing process in order to slow it down. Because more processing power is needed for each attempt, brute-force attacks become slower as a result. Key stretching is used in algorithms like bcrypt, scrypt, and PBKDF2.
  • Peppering − Before hashing passwords, a secret value (pepper) is added. This method is known as peppering. The pepper is not stored in the database, instead, it is stored separately from the hashed passwords. Because an attacker needs both the hashed passwords and the pepper to try to crack the passwords, this adds another level of security.

Algorithm for Hashing Password

Passwords are often securely hashed using a several techniques. There are a few of the most commonly used algorithms −

  • bcrypt
  • scrypt
  • Argon2
  • PBKDF2
  • SHA-256/SHA-3

Implementation of Hashing Passwords

Using Python

Now we will implement the python code for hashing password and we are going to use hashlib library of Python to generate the hash object. So the code is as follows −

import hashlib

def hash_password(password):
   # change the password to bytes
   password_bytes = password.encode('utf-8')

   # generate a SHA-256 hash object
   hash_object = hashlib.sha256()

   # update the hash object with the password bytes
   hash_object.update(password_bytes)

   # the hexadecimal representation of the hashed password
   hashed_password = hash_object.hexdigest()

   return hashed_password

# function execution
password = "mysecure@password"
hashed_password = hash_password(password)
print("Hashed password:", hashed_password)

Output

Hashed password: dc12e653439f07e6b0ee268b5559b45bb99be057dd7edd8756d77ef96b21aaee

Using Java

In this implementation we are going to use java.security.MessageDigest and java.security.NoSuchAlgorithmException classes of Java. So MessageDigest will be used to generate the message digest instance and NoSuchAlgorithmException class is used to throw the exception if no such algorithm found. So the code is as follows −

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashingPassword  {
   public static String hashPassword(String password) throws NoSuchAlgorithmException {
      // Create a MessageDigest instance
      MessageDigest digest = MessageDigest.getInstance("SHA-256");

      // the bytes of the password
      byte[] passwordBytes = password.getBytes();

      // update the digest with the password bytes
      digest.update(passwordBytes);

      // get the hashed bytes
      byte[] hashedBytes = digest.digest();

      // change the hashed bytes to hexadecimal
      StringBuilder hexString = new StringBuilder();
      for (byte hashedByte : hashedBytes) {
         hexString.append(String.format("%02x", hashedByte));
      }

      return hexString.toString();
   }

   public static void main(String[] args) throws NoSuchAlgorithmException {
      String password = "mysecure@password";
      String hashedPassword = hashPassword(password);
      System.out.println("Hashed password: " + hashedPassword);
   }
}

Output

Hashed password: dc12e653439f07e6b0ee268b5559b45bb99be057dd7edd8756d77ef96b21aaee
Advertisements