- Published on
Java Security - Part 4: Symmetric encryption algorithms in Java (e.g., AES, DES)
- Authors
- Name
- Gary Huynh
- @huynhthienthach
Aye, aye, Captain! We're back on the encryption
sea, sailing towards Symmetric Encryption
Island! Prepare yourself, matey, because we're about to crack the treasure chest of symmetric encryption algorithms
, like AES
and DES
.
But what be this Symmetric Encryption
, Cap'n? I hear you ask.
Well, Symmetric Encryption
, me hearty, is like a secret pirate handshake. The same secret code (or key
) is used to lock (or encrypt
) and unlock (or decrypt
) your treasure map (or data
). This be why it's called symmetric
, because it's the same
key on both sides!
Now, there are two well-known algorithms for this Symmetric Encryption
dance - the DES (Data Encryption Standard)
and the AES (Advanced Encryption Standard)
.
DES
: This ol' matey was one of the firstencryption standards
, introduced back in the '70s. But beware, me hearty!DES
uses a56-bit
key, and in our modern, high-tech pirate world, that's easier to crack than a stale biscuit. These days, it's more of a historical curiosity than a good choice for new applications.AES
: This be the new swashbuckler on deck, and it's much tougher to crack.AES
uses keys of128
,192
, or256 bits
, making it significantly more secure. It's the standard these days for most applications.
Enough talk, let's see how it works in our trusty ol' Java code:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class SymmetricEncryptionSample {
public static void main(String[] args) throws Exception {
// Generate an AES key
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
// Create a cipher
Cipher cipher = Cipher.getInstance("AES");
// Initialize the cipher for encryption
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// Encrypt a message
byte[] message = "Shiver me timbers, we're encrypting!".getBytes();
byte[] encryptedMessage = cipher.doFinal(message);
// Now let's decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedMessage = cipher.doFinal(encryptedMessage);
// And the message is...
System.out.println(new String(decryptedMessage));
}
}
In this example, we're using AES encryption
with a key size of 128 bits
to encrypt
and decrypt
our message.
In conclusion, symmetric encryption
be a powerful tool in our pirate coding arsenal. Just remember, keep your secret key safe! No self-respecting pirate wants their treasure maps falling into the wrong hands.
Stick around, matey! In our next episode, we'll be exploring the mysterious land of Asymmetric Encryption
. Till then, may your code be bug-free, and your coffers full of gold!