Published on

Java Security - Part 13: Secure storage of sensitive information in Java (passwords, credentials)

Authors

Ahoy, matey! We've arrived at the treasure trove of Secure Storage of Sensitive Information in Java. This ain't about hoarding gold coins, but it's every bit as important. We're talkin' about how to keep your precious jewels - I mean, passwords and credentials - safe from the prying eyes of scurvy pirates.

Let's start with the basics: never, ever, EVER store passwords in plaintext. That'd be like leaving your treasure chest in the middle of the deck with a sign that says "Please do not touch". Not exactly secure, eh?

Instead, we want to use a process called hashing to transform our password into a jumbled mess that's no use to anyone. We might also add a bit of salt to make it even harder to crack. Not table salt, mind you - in cryptography, a salt is random data that you use as extra input to a hashing function.

Java's got several ways to do this, but let's stick with the Spring Security library, since it's mighty handy for this sort of thing.

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class PasswordEncoder {
    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String rawPassword = "parrot";
        String encodedPassword = encoder.encode(rawPassword);

        System.out.println(encodedPassword);
    }
}

In this snippet, we're using BCrypt to hash the password. Even if some scurvy dog gets their hands on the hashed password, they won't be able to reverse-engineer it to get the original password. Plus, every time you run this, you'll get a different output because of the salt.

One more thing: don't forget to store your secret keys and sensitive config data securely too! You could use environment variables, or a secure vault like HashiCorp's Vault, or cloud service solutions like AWS Secrets Manager.

Now you're ready to protect your treasure - I mean, your passwords and other sensitive data. Next, we're going to navigate the treacherous waters of common security vulnerabilities in Java. Hold onto your hats!