Home > Java > javaTutorial > body text

How can I securely encrypt passwords stored in configuration files using Java's Password Based Encryption?

Mary-Kate Olsen
Release: 2024-11-17 04:17:03
Original
683 people have browsed it

How can I securely encrypt passwords stored in configuration files using Java's Password Based Encryption?

Encrypting Passwords in Configuration Files

Protecting passwords stored in configuration files is crucial. Here's a secure approach using Java's Password Based Encryption:

Problem Overview:

Encrypting passwords in configuration files allows secure storage and retrieval by programs. This method prevents sensitive information from being compromised.

Java's Password Based Encryption Solution:

Java's Password Based Encryption (PBE) provides a convenient way to encrypt and decrypt passwords using a password-based key. It involves the following steps:

  • Initialize a Cipher object with the "AES/CBC/PKCS5Padding" algorithm.
  • Calculate a javax.crypto.SecretKey from the password using a javax.crypto.SecretKeyFactory with the "PBKDF2WithHmacSHA512" algorithm.

Code Example:

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.InvalidKeySpecException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PBEKeySpec;
import java.util.Base64;

public class PasswordEncryption {

    public static void main(String[] args) throws Exception {
        // Generate a secret key from the password
        char[] password = "mySecurePassword".toCharArray();
        byte[] salt = new String("12345678").getBytes();
        int iterationCount = 40000;
        int keyLength = 128;
        SecretKeySpec key = createSecretKey(password, salt, iterationCount, keyLength);

        // Encrypt a password using the secret key
        String originalPassword = "secretPassword";
        String encryptedPassword = encrypt(originalPassword, key);

        // Decrypt the encrypted password
        String decryptedPassword = decrypt(encryptedPassword, key);
    }

    private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
        PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        return new SecretKeySpec(keyTmp.getEncoded(), "AES");
    }

    private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters parameters = cipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
        byte[] cryptoText = cipher.doFinal(property.getBytes("UTF-8"));
        byte[] iv = ivParameterSpec.getIV();
        return base64Encode(iv) + ":" + base64Encode(cryptoText);
    }

    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
        String iv = string.split(":")[0];
        String property = string.split(":")[1];
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
        return new String(cipher.doFinal(base64Decode(property)), "UTF-8");
    }

    private static byte[] base64Decode(String property) throws IOException {
        return Base64.getDecoder().decode(property);
    }
}
Copy after login

Security Considerations:

This method utilizes a strong encryption algorithm (AES) and a secure key derivation function (PBKDF2WithHmacSHA512). It is crucial to choose a strong password and store it securely.

Storing the Master Password:

The password used to encrypt the configuration file requires secure storage. Store it in an environment variable or a separate secure location.

The above is the detailed content of How can I securely encrypt passwords stored in configuration files using Java's Password Based Encryption?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template