Explain Codes LogoExplain Codes Logo

How to encrypt String in Java

java
cryptography
security-best-practices
key-management
Nikita BarsukovbyNikita BarsukovΒ·Feb 17, 2025
⚑TLDR

Get cracking with AES encryption in Java using this no-nonsense snippet:

import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Main { public static void main(String[] args) throws Exception { byte[] key = "1234567890123456".getBytes(); // Use your own key and don't tell your 🐢 SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); String plainText = "Encrypt this!"; byte[] encryptedBytes = cipher.doFinal(plainText.getBytes()); // Convert to Base64 because nobody can read πŸ˜΅β€πŸ’« binary, am I right? String encryptedText = java.util.Base64.getEncoder().encodeToString(encryptedBytes); // Voila! Your encrypted String: encryptedText } }

Remember, your key should be as predictable as a coin toss πŸͺ™! And swap the plainText with your secret message.

Fortifying the fort: Advanced encryption practices

To shield your data fortress, here's your high-grade security blueprint:

Mode selection: Your security's architect

Just like you wouldn't build a castle on sand, don't base your security on ECB. Go for its beefier relative AES/GCM/NoPadding.

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

Extra strong, please! Upping your password game

Passwords are like toothbrushes β€” the longer and more complex, the better. Use a key derivation function called PBKDF2 for an extra edge.

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength); SecretKeySpec key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");

Key management: The unsung hero

Key management can make or break your castle. Avoid hardcoded keys like you would avoid the plague πŸ‘Ύ.

Cryptography libraries: The silent guardians

Don't flex those coding muscles unnecessarily! Go for tried and tested libraries like Tink or Bouncy Castle:

// Here's Tink doing its magic πŸ‘¨β€πŸ”¬ KeysetHandle keysetHandle = KeysetHandle.generateNew(AeadKeyTemplates.AES256_GCM); Aead aead = keysetHandle.getPrimitive(Aead.class);

Sensitive data management: The cleaner you never knew you needed

Sensitive data is like spider websβ€”clean them ASAP! Always handle keys or plaintext as byte arrays and clear them post-use.

Brick by brick: Building a secure groundwork

Platform-agnostic encryption: For all seasons

Choose an encryption method that's as adaptable as a chameleon 🦎, ensuring cross-platform compatibility.

Prepping the data: The pre-party

Objects to be encrypted need not be party poopers. Convert them to/from byte arrays for seamless encryption/decryption.

Exception handling: The bouncer

Tackle exceptions with skill to avoid data spill. Remember, the cleanup is as important as the party!

Keeping tabs: The know-it-all

Security trends change faster than fashion. Stay updated to strut your secure runway!