Are you ready to level up your Java skills and build something super practical and secure?
In this post, weโre building a Java-based Password Manager that stores your secrets encrypted using AES (Advanced Encryption Standard). No more storing passwords in plain text โ itโs time to code like a security pro!
๐ก What Youโll Learn
- How to use AES encryption/decryption in Java
- How to read/write encrypted data to a file
- How to build a console-based password manager
- How to safely store and retrieve sensitive credentials
๐ ๏ธ Tools Youโll Need
- Java 8 or above
- Any code editor (VS Code, IntelliJ, etc.)
- A terminal to run the program
๐ฆ Project Features
- Add an account (username + password)
- List saved accounts
- Store everything encrypted in a local file
- All data is decrypted only when viewed
๐งพ Full Source Code
PasswordManager.java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class PasswordManager {
private static final String FILE_NAME = "passwords.txt";
private static final String SECRET_KEY = "mySuperSecretKey"; // Used for AES key generation
private static Map<String, String> credentials = new HashMap<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
loadCredentials();
while (true) {
System.out.println("\n--- Password Manager ---");
System.out.println("1. Add Account");
System.out.println("2. View Accounts");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
String choice = scanner.nextLine();
switch (choice) {
case "1":
System.out.print("Enter Account Name: ");
String account = scanner.nextLine();
System.out.print("Enter Password: ");
String password = scanner.nextLine();
addAccount(account, password);
break;
case "2":
viewAccounts();
break;
case "3":
System.out.println("Exiting...");
saveCredentials();
return;
default:
System.out.println("Invalid choice.");
}
}
}
private static void addAccount(String account, String password) {
try {
String encryptedPassword = encrypt(password, SECRET_KEY);
credentials.put(account, encryptedPassword);
System.out.println("Account added successfully!");
} catch (Exception e) {
System.out.println("Failed to encrypt password.");
}
}
private static void viewAccounts() {
System.out.println("\n--- Saved Accounts ---");
for (Map.Entry<String, String> entry : credentials.entrySet()) {
try {
String decryptedPassword = decrypt(entry.getValue(), SECRET_KEY);
System.out.println("Account: " + entry.getKey() + " | Password: " + decryptedPassword);
} catch (Exception e) {
System.out.println("Failed to decrypt password for " + entry.getKey());
}
}
}
private static void saveCredentials() {
try (PrintWriter writer = new PrintWriter(new FileWriter(FILE_NAME))) {
for (Map.Entry<String, String> entry : credentials.entrySet()) {
writer.println(entry.getKey() + ":" + entry.getValue());
}
} catch (IOException e) {
System.out.println("Failed to save credentials.");
}
}
private static void loadCredentials() {
File file = new File(FILE_NAME);
if (!file.exists()) return;
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2);
if (parts.length == 2) {
credentials.put(parts[0], parts[1]);
}
}
} catch (IOException e) {
System.out.println("Failed to load credentials.");
}
}
private static String encrypt(String data, String secret) throws Exception {
SecretKeySpec key = getKey(secret);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
private static String decrypt(String encryptedData, String secret) throws Exception {
SecretKeySpec key = getKey(secret);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(original);
}
private static SecretKeySpec getKey(String myKey) throws Exception {
byte[] key = myKey.getBytes("UTF-8");
return new SecretKeySpec(key, 0, 16, "AES");
}
}
๐ Line-by-Line Breakdown
๐ Encryption and Decryption
Cipher cipher = Cipher.getInstance("AES");
This initializes an AES cipher. AES is a widely used encryption algorithm.
cipher.init(Cipher.ENCRYPT_MODE, key);
We initialize the cipher for encryption mode with a secret key.
Base64.getEncoder().encodeToString(encrypted);
Encrypted bytes are converted to a Base64 string so we can store them as text.
cipher.init(Cipher.DECRYPT_MODE, key);
Same cipher, now used to decrypt the encrypted string back to the original password.
๐ File Handling
PrintWriter writer = new PrintWriter(new FileWriter(FILE_NAME));
We open the file for writing the encrypted credentials.
String[] parts = line.split(":", 2);
Splits each line into account and encrypted password while loading saved credentials.
๐ Menu and Interaction
System.out.println("1. Add Account");
This is your menu โ simple and intuitive.
credentials.put(account, encryptedPassword);
Stores the encrypted password in the Map
.
โ ๏ธ Security Notes
- Do not hardcode secret keys in production apps.
- Use a key derivation function (KDF) for real-world applications.
- For serious apps, add salt and authentication (HMAC).
๐ก Bonus Ideas
- Add a master password to unlock the manager
- Create a JavaFX GUI
- Export/import data securely
- Add password strength validation
โ Final Output Preview
--- Password Manager ---
1. Add Account
2. View Accounts
3. Exit
Choose an option: 2
--- Saved Accounts ---
Account: Gmail | Password: mySecurePass123
Account: GitHub | Password: code4life
๐ Wrapping Up
You just built a real-world secure password manager using nothing but Java and AES encryption! This project gives you valuable experience with:
- Java file I/O
- Encryption
- Data persistence
- Console apps
๐ฌ Tell Me What You Think!
Liked the post? Drop a comment or share it with your Java friends. More security-based Java projects coming soon!
๐๏ธ Written by Devesh โ simplifying code, one project at a time.