Encrypting passwords helps protect them from unauthorized access. In this article, we will see how to encrypt passwords in configuration files and decrypt them in a Java program when needed.

Choosing encryption algorithm

Before encrypting and decrypting passwords, we need to select an encryption algorithm. Java provides various encryption algorithms.

The commonly used algorithm is the Advanced Encryption Standard (AES). We can use AES for symmetric encryption, where the same key is used for both encryption and decryption.

Generate an Encryption Key

To encrypt and decrypt data using AES, we need an encryption key. This key is very important and should be secured at any cost because it’s a secret used for both encryption and decryption. We can generate a secure key using Java’s KeyGenerator class. Following is an example:

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;

public class KeyGenerationExample {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        // Generate a secure AES encryption key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256); // Key size (in bits)

        SecretKey secretKey = keyGenerator.generateKey();

        // Save the secretKey securely for later decryption
        // ...
    }
}

In the above example, we use AES with a 256-bit key size, but the key size can be adjusted based on the security requirements.

Encrypt the password

Once we have a secret key, we can use it to encrypt a password and save it in the configuration file. Following is an example:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class PasswordEncryptionExample {

    public static void main(String[] args) throws Exception {
        // Replace with your actual password
        String passwordToEncrypt = "MySecretPassword";

        // Load the secretKey (previously generated) securely
        byte[] secretKeyBytes = /* Load the key as bytes */;

        SecretKey secretKey = new SecretKeySpec(secretKeyBytes, "AES");

        // Initialize the AES Cipher
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // Encrypt the password
        byte[] encryptedPasswordBytes = cipher.doFinal(passwordToEncrypt.getBytes(StandardCharsets.UTF_8));

        // Encode the encrypted bytes as a base64 string
        String encryptedPassword = Base64.getEncoder().encodeToString(encryptedPasswordBytes);

        // Save the encrypted password in your configuration file
        System.out.println("Encrypted Password: " + encryptedPassword);
    }
}

Explanation:

In the above example, we loaded the secret key securely and initialized an AES cypher to encrypt the password. Finally, we encode the encrypted bytes as a base64 string for storage in the configuration file.

Decrypt the password

To use the encrypted password in your Java program, we need to decrypt it. Here’s how we can do it:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class PasswordDecryptionExample {

    public static void main(String[] args) throws Exception {
        // Load the encrypted password from your configuration file
        String encryptedPassword = "/* Encrypted password from configuration */";

        // Load the secretKey (previously generated) securely
        byte[] secretKeyBytes = /* Load the key as bytes */;

        SecretKey secretKey = new SecretKeySpec(secretKeyBytes, "AES");

        // Initialize the AES Cipher for decryption
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // Decode the base64 string and decrypt the password
        byte[] encryptedPasswordBytes = Base64.getDecoder().decode(encryptedPassword);
        byte[] decryptedPasswordBytes = cipher.doFinal(encryptedPasswordBytes);

        // Convert the decrypted bytes back to a string
        String decryptedPassword = new String(decryptedPasswordBytes, StandardCharsets.UTF_8);

        System.out.println("Decrypted Password: " + decryptedPassword);
    }
}

In the above example, we load the encrypted password from the configuration file, initialize an AES cipher for decryption, decode the base64 string, and finally convert the decrypted bytes back to a string, which reveals the original password.

Categorized in:

Tagged in: