DEV Community

Deep Nikode
Deep Nikode

Posted on

Enhancing Data Security with AES Encryption in Java 🚀🔒

Encryption is a fundamental aspect of Information Security practice to protect sensitive data. There could be several use cases to encrypt data to hide sensitive information like password, card details, contact details, and several other details.🔑

The AES Algorithm requires a plain-text and a secret key for encryption and the same secret key is required again to decrypt it.

🔍 How It Works

THEORY

  • Encryption: Converts plain text into a secure, encrypted format using the AES algorithm.

  • Decryption: Reverts the encrypted data back to its original form, ensuring data integrity and confidentiality.

  • Key Generation: Uses a hardcoded key for encryption and decryption. This key is critical for both processes.

AES

CODE

I'm excited to share a recent code snippet I developed for my Project, demonstrating how to implement AES encryption and decryption in Java. 🌐👨‍💻

  • Constants:
  1. ALGORITHM: Set to "AES", specifying the encryption algorithm.
  2. KEY: A byte array derived from the string "MySuperSecretKey". This is used as the encryption key.
private static final String ALGORITHM = "AES";
private static final byte[] KEY = "deepNikodeCoderr".getBytes(StandardCharsets.UTF_8);
Enter fullscreen mode Exit fullscreen mode
  • Encryption Method (encrypt)
public static String encrypt(String data) throws Exception 
{

        Key key = generateKey();


        //Creates a Cipher object for AES.
        Cipher cipher = Cipher.getInstance(ALGORITHM); 


        //Initializes the cipher for encryption.
        cipher.init(Cipher.ENCRYPT_MODE, key);


        //Performs the actual encryption.
        byte[] encryptedValue = cipher.doFinal(data.getBytes());

      //converts encrypted bytes to a Base64 string.
        return java.util.Base64.getEncoder().encodeToString(encryptedValue);
}
Enter fullscreen mode Exit fullscreen mode
  • Decryption Method (decrypt)
public static String decrypt(String encryptedData) throws Exception 
{
        Key key = generateKey();
        Cipher cipher = Cipher.getInstance(ALGORITHM);

      //Initializes for decryption.
        cipher.init(Cipher.DECRYPT_MODE, key);

      //converts the Base64 string back to bytes.
        byte[] decodedValue = java.util.Base64.getDecoder().decode(encryptedData);

      //Performs the actual decryption.
        byte[] decryptedValue = cipher.doFinal(decodedValue);

        return new String(decryptedValue);
}
Enter fullscreen mode Exit fullscreen mode
  • Key Generation Method (generateKey)
private static Key generateKey() 
{
        return new SecretKeySpec(KEY, ALGORITHM);
}
Enter fullscreen mode Exit fullscreen mode

I hope this snippet helps you in your projects and encourages more developers to prioritize data security. Feel free to reach out if you have any questions or suggestions!

My Code

Stay secure, and happy coding! 💻✨

Top comments (0)