Get 50% Discount Offer 26 Days

Recommended Services
Supported Scripts
WordPress
Hubspot
Joomla
Drupal
Wix
Shopify
Magento
Typeo3
How to Convert a Password to a Hash in Linux

Securing sensitive data is essential for maintaining a stable and trustworthy IT ecosystem, especially in Linux environments. One fundamental practice in modern cybersecurity is converting plain-text passwords into cryptographic hashes. In Linux, password hashing is crucial in preventing unauthorized access, data breaches, and misuse of user credentials. Rather than storing passwords in plain text, Linux systems use hashing algorithms to produce secure, one-way representations of those passwords.

This detailed guide introduces the reader to the intricacies of password hashing, why you need hashing to strengthen Linux security, the formats available in today’s market, and how to make hashed passwords for users. It also provides good practices and presents topics that usually provoke minor security problems to facilitate your security processes. The Linux Administration: Bootcamp Training for Linux System Administrators course explains the process of converting passwords to hashes by the end of this lesson and how to enhance your systems’ security.

Understanding Password Hashing

Password hashing transforms a plain-text password into a seemingly random string of characters known as a “hash.” This transformation is performed by a cryptographic function designed to be irreversible. When a user attempts to log in, the provided password is hashed using the same function, and the system compares the new hash to the stored hash. If they match, authentication is granted.

Unlike encryption, hashing is meant to be one-way. There is no straightforward method to revert a hash to its original content. This distinct property makes hashing ideal for storing sensitive data such as user passwords. Even if an attacker accesses the hashed passwords, reversing them to plain Text is computationally unfeasible if modern hashing algorithms and practices are used.

Why Password Hashing Is Crucial for Linux Security

Protecting Against Data Breaches

A primary reason password hashing is crucial is that it mitigates the impact of data breaches. If passwords were stored in plain Text, unauthorized individuals accessing user credentials could log in immediately and gain full privileges. With hashed passwords, attackers only obtain a one-way representation of the passwords. They must then attempt computationally expensive methods, such as brute-force or dictionary attacks, to guess the original password. Strong hashing algorithms and good password complexity make these attacks exceedingly tricky.

Preventing Insider Threats

Even individuals with legitimate access to system files can pose a potential risk. If system administrators or other privileged users could read passwords in plain text, they might exploit these credentials elsewhere. By storing hashed passwords, you ensure that even high-level users cannot directly see or misappropriate those passwords.

Meeting Compliance Requirements

Different laws, such as the EU’s GDPR or principles, including the PCI DSS, require keeping user credentials safe. This is why organizations use strong password hashing to overcome compliance requirements. Failure to do the above may attract legal consequences and financial repercussions, as well as damaging a company’s reputation.

Enhancing Overall Security Posture

Password hashing cannot singlehandedly secure a system, but it is a key building block in a broader cybersecurity strategy. When implemented alongside strong access controls, regular patching, network monitoring, and other security measures, password hashing helps create a layered defense that is significantly harder to penetrate.

Key Password Hashing Algorithms

MD5

MD5, which stands for Message-Digest Algorithm 5, has historically been a common choice for hashing. It produces a 128-bit hash value. While it served its purpose earlier, it is now considered outdated and vulnerable to collision-based attacks. Modern computer hardware can crack MD5-hashed passwords with relative ease, making it unsuitable for storing passwords in any contemporary environment.

SHA-1

SHA-1 (Secure Hash Algorithm 1) was once seen as the logical successor to MD5. Generating a 160-bit hash, SHA-1 enjoyed extensive adoption in various applications. However, multiple vulnerabilities and collision attacks have proven that SHA-1 is similarly not ideal for high-security requirements. Its usage for password hashing is strongly discouraged in current best practices.

SHA-256

SHA-256 is part of the SHA-2 family and produces a 256-bit hash value. It is significantly more secure than either MD5 or SHA-1. SHA-256 is used across many modern applications, from secure certificates to data integrity checks. When used in password hashing, the length of the hash and the difficulty in reversing it provide better security, mainly if you employ salting to diversify the resulting outputs.

SHA-512

SHA-512, also part of the SHA-2 family, generates a 512-bit hash. It is computationally more intensive and provides a broader hash space than SHA-256, making it harder to brute-force in theory. Many Linux distributions default to SHA-512 for password hashing due to its longer hash length and improved resilience against attacks. However, both SHA-256 and SHA-512 typically require the incorporation of salts to provide robust security.

bcrypt

crypt is specifically designed for password hashing. It integrates a cost factor, which adjusts how computationally tricky the hashing process is. This concept, known as key stretching, makes bcrypt more resilient to brute-force attacks because attackers must spend far more time attempting to crack each password. bcrypt also generates a salt by default, ensuring each hash is unique.

Argon2

Argon2 is a modern, high-security password hashing function that won the Password Hashing Competition (PHC). It offers memory-hard properties, which can be configured to use large amounts of RAM, hindering highly parallelized attacks on GPUs or specialized hardware. Argon2 comes in several variants, including Argon2i, Argon2d, and Argon2id, each offering different balances of security features. This algorithm is considered state-of-the-art and is strongly recommended when you want the highest level of protection.

Importance of Salts in Password Hashing

A salt is a random string appended or prepended to the password before hashing. Its primary function is to ensure that the same password does not always hash to the same value. This eliminates using rainbow tables, precomputed tables that map common hashes back to their plain-text passwords. If salts are applied correctly, attackers would need a unique set of rainbow tables for each salt, drastically increasing the complexity and computational overhead of cracking attempts.

Salts also ensures two users with the same password have entirely different hashes. Beyond salts, some organizations also utilize a “pepper,” a secret value stored securely outside the main configuration or database. Using a pepper further complicates an attacker’s job because even if they have the hash and the salt, they still lack the pepper necessary to perform accurate brute-force attempts.

How Linux Stores and Manages Passwords

Linux relies on dedicated files to store and reference user credentials. Historically, user data and hashed passwords were combined in a single file, but security concerns led to the current practice of splitting them into two separate files.

/etc/passwd

The /etc/passwd file contains essential user information like username, user ID (UID), group ID (GID), home directory path, and default shell. On modern systems, the password field in /etc/passwd is replaced with an “x” or “*,” indicating that the password is stored elsewhere. While /etc/passwd is world-readable (for compatibility reasons), it should not contain actual password hashes.

Linux etc passwd file displaying user data including UID GID and default shell info

/etc/shadow

The /etc/shadow file holds the hashed passwords and additional security and account details, such as password expiration policies and inactivity periods. Root alone can view this file or processes with appropriate privileges. When a user logs in, the operating system references this file to compare the hashed representation of the password they just typed to the stored hash.

Linux etc shadow file showing hashed passwords and account security details

With /etc/shadow controlling password hashes, it becomes more difficult for unauthorized users or prying eyes to glean information about system accounts. Proper file permissions on /etc/shadow are critical for maintaining a high-security environment.

Methods to Convert Passwords to Hashes in Linux

There are several methods of creating hashed passwords using command-line tools, libraries, and programming on the Linux operating system. Your chosen method depends on your needs, whether you are willing to work with native utilities or use a scripting language such as Python.

Using OpenSSL passwd

OpenSSL is recognized for its crucial role in TLS/SSL encryption, but it also includes a handy command-line tool called openssl passwd. This command creates hashed passwords using different algorithms, including MD5, SHA-256, and SHA-512. By default, many modern Linux distributions use SHA-512 when the -6 flag is supplied.

Example command:

openssl passwd -6 MySecretPassword
OpenSSL passwd command creating a SHA-512 hashed password example output

The output will be a SHA-512-based hashed password. If you need a different algorithm, other flags like -1 for MD5 or -5 SHA-256 might be available on your distribution.

Using mkpasswd from the whois Package

Another convenient utility for generating password hashes is mkpasswd, which is part of the whois package on many Linux systems. It supports algorithms such as MD5, SHA-256, SHA-512, and even bcrypt in some implementations.

Example command:

mkpasswd --method=sha-512 MySecretPassword --salt=RandomSaltValue
Linux mkpasswd command using SHA-512 and salt to generate a secure hashed password

If you omit the –salt parameter, the tool will generate one for you, ensuring each hash remains unique. This simplicity and flexibility make mkpasswd a favorite for quick, interactive password hashing.

Using crypt() in a Shell Script

Linux systems typically include a C library function called crypt(), a common low-level mechanism for generating hashed passwords. You can tap into crypt() through various scripting or programming languages (C, Perl, Python, etc.). Many shell scripts rely on external tools like openssl passwd or mkpasswd rather than directly calling crypt(). Still, crypt() remains a foundational component for hash generation on Linux.

Using Python’s hashlib Module

Original hashlib, the standard feature of the Python framework, can then create hashes using algorithms such as SHA-256 and SHA-512. However, it does not have a native key stretching feature, which does not handle salts or cost factors like bcrypt. You must write your salt logic or use third-party frameworks to prevent it.

Example snippet:

import hashlib

password = "MySecretPassword"
encoded_password = password.encode('utf-8')
hash_object = hashlib.sha256(encoded_password)
hashed_password = hash_object.hexdigest()
print(hashed_password)
Python script using hashlib library to generate SHA-256 hashed password

While simple, this approach is best suited for scenarios where you manually manage salts or non-production tasks that do not require advanced key stretching algorithms.

Using Python’s passlib Library

For firmer password handling in Python, the passlib library offers built-in support for bcrypt, Argon2, PBKDF2, and other modern algorithms. passlib also handles salt generation, making it easier to produce robust passwords.

Example snippet:

From passlib.hash import bcrypt

password = "MySecretPassword"
hashed = bcrypt.hash(password)
print(hashed)

if bcrypt.verify(password, hashed):
    print("Password verification successful!")
else:
    print("Password verification failed.")
Python bcrypt example for password hashing and verification using passlib library

This approach is more secure than raw hashlib usage. passlib encourages best practices, meaning developers can focus on core application logic rather than intricately managing salts and cost factors.

Additional Utility-Based Approaches

Linux offers utilities such as htpasswd (commonly used with Apache) and tools in languages like Perl, Ruby, or Go, each featuring cryptographic libraries to generate hashed passwords. The core idea remains the same: you provide a password, possibly a salt, and the tool outputs a hashed result that you store securely.

Step-by-Step Examples of Password Hashing

Script-Based Example with OpenSSL passwd

Below is a small shell script illustrating how to automate password hashing using openssl passwd and store the resulting hash in a variable.

#!/bin/bash
# File: hash_password.sh
# Usage: ./hash_password.sh <plain_text_password>

if [ -z "$1" ]; then
  echo "Please provide a plain text password."
  exit 1
fi

PLAIN_PASSWORD="$1"
HASHED_PASSWORD=$(openssl passwd -6 "$PLAIN_PASSWORD")

echo "Generated hash: $HASHED_PASSWORD"
Bash script example using OpenSSL to hash plain text passwords with SHA-512

After saving this file and making it executable (chmod +x hash_password.sh)

Command to make a Bash script executable using chmod plus x in Linux terminal

, and run it with a password argument:

./hash_password.sh MySecretPassword
Running a Bash script to hash a password using OpenSSL with SHA-512 algorithm

The script prints an SHA-512-based hash, which you can insert into /etc/shadow or another secure location.

Interactive Shell Hash Generation with mkpasswd

If you need a one-off hash for a user account or test environment, mkpasswd provides an interactive way to generate it.

Install whois if needed:
sudo apt-get install whois

  • Run mkpasswd:
mkpasswd --method=sha-512
Using mkpasswd command with SHA-512 method to generate a secure hashed password
  • Enter the password when prompted. The resulting output is a SHA-512 hash that you can store or use in your configuration scripts.

Python Script Using passlib

For developers who prefer Python-based automation, here is a short example using passlib and the bcrypt algorithm.

#!/usr/bin/env python3
from passlib.hash import bcrypt
import sys

if len(sys.argv) < 2:
    print("Usage: {} <plaintext_password>".format(sys.argv[0]))
    sys.exit(1)

plaintext_password = sys.argv[1]
hashed_password = bcrypt.hash(plaintext_password)
print("Bcrypt Hash:", hashed_password)
Python script using passlib bcrypt to hash a password and display the output

After installing passlib (pip install passlib), you can run the script to generate secure bcrypt hashes. You can also integrate password verification in your code:

if bcrypt.verify(plaintext_password, hashed_password):
    print("Password matches the hash!")
else:
    print("Invalid password!")

This provides a simple and practical foundation for building secure authentication systems in Python.

Python script using passlib bcrypt for password hashing and verification process

Verifying and Managing Hashed Passwords

Hash generation is only half the story. Once you have hashed passwords stored, proper verification and lifecycle management are equally important. In a typical Linux login process, the system automatically checks a hashed password in /etc/shadow against the user’s input using the appropriate cryptographic function. Access is granted or denied according to whether the hashes match.

Linux etc shadow file demonstrating hashed passwords and lifecycle management

A similar verification step is vital when building custom applications. Many libraries, such as passlib, handle this straightforwardly, abstracting the complexity of salt retrieval and cost factors.

Management of hashed passwords involves:

  • Rotating outdated algorithms if new vulnerabilities are discovered.
  • Regularly auditing permission settings ensures that only authorized processes or users can view the hash files.
  • Implementing password aging policies to enforce periodic password changes reduces the risk of compromised passwords remaining active for lengthy periods.

Best Practices for Strengthening Linux Password Security

Use Strong Salts and Pepper

Always incorporate a salt of sufficient length and randomness. This ensures that their hashes differ even if two users use the same password. Consider using a secret value stored in a highly secure location (like an environment variable or a hardware security module) for additional security. This makes it even more difficult for attackers to guess the original password, as they must also know the pepper.

Choose Modern Hashing Algorithms

Avoid archaic algorithms like MD5 or SHA-1. Opt instead for bcrypt, Argon2, PBKDF2, or at least SHA-512 with a significant iteration count. These algorithms have stood up to modern attacks more robustly. If performance becomes a concern, incrementally adjust the cost parameters (for bcrypt) or memory/time parameters (for Argon2) to balance security and resource utilization.

Enforce Proper File Permissions

Restricting access to /etc/shadow is essential. By default, only the root user should be able to read or modify this file. Regularly verify permissions, monitor changes with tools like auditd, and do not allow unnecessary user or process access. Consider implementing mandatory access control (MAC) systems like SELinux or AppArmor for an extra layer of protection.

Linux etc shadow file showing proper file permissions for secure access control

Implement Password Complexity Rules

Weak or predictable passwords compromise even the most robust hashing solutions. Use tools like pam_cracklib or pam_pwquality to enforce complexity rules, such as a minimum length, inclusion of alphanumeric characters, and usage of special symbols. Educate users on choosing difficult-to-guess passwords to minimize successful brute-force attempts.

Require Password Rotation

The following should be in place to allow users to change passwords periodically. Provide password expiration policies. , although contrarily, it can become an issue of usability if done too frequently; it is essential to maintain the proper balance. Rotating passwords is a step up from a cracked password where one credential stays open for business for the foreseeable future. This combines account lockout policies to avoid multiple brute-force password attempts.

Enable Multi-Factor Authentication

Hashing alone will not secure credentials if an attacker learns a valid password. Multi-factor authentication (MFA) or two-factor authentication (2FA) adds a second layer of security. Requiring an additional token or code, perhaps via a smartphone app or a hardware key system, becomes significantly more challenging to breach, even if a password is leaked.

Conduct Regular Security Audits

Security is dynamic. New forms of vulnerability are occasionally discovered, and attackers practice new tricks. Regular security assessments should be performed, of which penetration testing and vulnerability assessments should be part. Ensure you use the top hash algorithms, the proper file permissions, and password policies for the current year. Stay informed about emerging cryptographic weaknesses and be prepared to migrate to newer hashing algorithms when needed.

Common Pitfalls and How to Avoid Them

Using Insecure Algorithms

Many systems still rely on legacy algorithms like MD5 or SHA-1 for compatibility. Make it a priority to migrate to safer methods, such as bcrypt or Argon2. The cost of maintaining insecure systems can be far higher in the event of a breach than the effort required to upgrade your encryption and hashing solutions.

Forgetting to Incorporate Salts

Storing unsalted hashes is a glaring security flaw. It leaves passwords vulnerable to rainbow table attacks and reduces the effectiveness of your hashing efforts. Ensure your chosen library or tool automatically generates salts or that you implement a salt yourself. Always store the salt alongside the hashed password in a secure format (e.g., inside the same string structure).

Storing Passwords in Plain Text

This is a cardinal sin in information security. Plain-text passwords provide attackers with immediate access to user accounts and the potential to leverage those credentials elsewhere. Even storing them briefly in logs or cache files can pose a significant risk. Always hash passwords immediately upon receiving them, and carefully sanitize logs to prevent accidental disclosure.

Mismanagement of Permissions and Access Controls

Overly permissive file settings and user privileges can render robust hashing moot—review which users or groups can read sensitive data and remove unnecessary permissions. Deploy advanced security frameworks like SELinux to enforce strict policy-based controls, even for privileged processes.

Skipping or Neglecting Regular Updates

Over time, some hashing algorithms or library implementations become deprecated or identified as vulnerable. Regularly patch and update your systems, libraries, and dependencies. Stay informed about vendor security advisories and apply recommended updates to open-source communities. Even the best hash functions require up-to-date software to ensure vulnerabilities are not lurking in outdated implementations.

Conclusion

Encrypting passwords in Linux form is necessary to provide more safety for users. By using hash passwords and storing them accordingly, sysadmins and developers can reduce the impact of attacks and the loss of people’s identities. Besides implementing the strong hashing algorithm, unique salt, proper file permission, and suitable measures such as MFA, today’s cybersecurity risks can be proficiently overcome.

This guide explored why password hashing is vital for Linux security and how various algorithms such as SHA-512, bcrypt, and Argon2 offer distinct advantages. We covered practical ways to generate hashes, including command-line tools like openssl passwd and mkpasswd and Python libraries like hashlib and passlib. Additionally, we delved into best practices, emphasizing password complexity, rotation, and regular security audits.

The aim was to enhance Linux’s password protection; it is not a single-effort process but a continuous process. If these hashing operations are synchronized with the progress made in cryptographic research and new threats, your strategies are perfect. The steps form the basis of a multi-layered security model, from denying read access to a file such as /etc/shadow to ensuring read is the only access possible.

By adding time to work on complex hashing techniques and strict security measures, you also minimize the possible threats to sensitive data. By keeping informed of threats and techniques currently being used, you can ensure that your Linux systems are protected over the long term and stable and secure.

About the writer

Vinayak Baranwal Article Author

Vinayak Baranwal wrote this article. Use the provided link to connect with Vinayak on LinkedIn for more insightful content or collaboration opportunities.

Leave a Reply

Your email address will not be published. Required fields are marked *

Lifetime Solutions:

VPS SSD

Lifetime Hosting

Lifetime Dedicated Servers