Symmetric Encryption Cryptography in Java


Introduction

Symmetric encryption, also known as secret-key encryption, is a type of encryption where the same key is used for encryption and decryption. This encryption method is fast and efficient, making it suitable for encrypting large amounts of data. The most commonly used symmetric encryption algorithm is the Advanced Encryption Standard (AES).

Java provides strong support for symmetric encryption with the javax.crypto package, which includes classes such as SecretKey, Cipher, and KeyGenerator.

Symmetric Encryption in Java

Java's Cipher class in the javax.crypto package provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.

In Java, the Cipher class provides the functionality for symmetric encryption, while the KeyGenerator class is used to generate secret keys for symmetric encryption.

Example

Let's look at a simple implementation of symmetric encryption using AES in Java −

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Main {
   public static void main(String[] args) throws Exception {

      // Generate key
      SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
   
      // Original message
      String originalMessage = "Hello, world!";
   
      // Create Cipher instance and initialize it to ENCRYPT_MODE
      Cipher cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
   
      // Encrypt the message
      byte[] encryptedMessage = cipher.doFinal(originalMessage.getBytes(StandardCharsets.UTF_8));
   
      // Convert the encrypted message to Base64 encoded string
      String encodedMessage = Base64.getEncoder().encodeToString(encryptedMessage);
   
      System.out.println("Original Message: " + originalMessage);
      System.out.println("Encrypted Message: " + encodedMessage);
   
      // Reinitialize the cipher to DECRYPT_MODE
      cipher.init(Cipher.DECRYPT_MODE, secretKey);
   
      // Decrypt the message
      byte[] decryptedMessage = cipher.doFinal(Base64.getDecoder().decode(encodedMessage));
   
      System.out.println("Decrypted Message: " + new String(decryptedMessage, StandardCharsets.UTF_8));
   }
}

Output

When you run the program, you'll see output similar to the following −

Original Message: Hello, world!
Encrypted Message: iWohhm/c89uBVaJ3j4YFkA==
Decrypted Message: Hello, world!

Explanation

In the code above, we first generate a secret key for AES encryption using the KeyGenerator class.

We then create an instance of the Cipher class for AES and initialize it to ENCRYPT_MODE with the secret key.

Next, we define an original message, "Hello, world!", and encrypt it using the Cipher's doFinal method. We also convert the encrypted message bytes to a Base64 encoded string to make it easier to handle.

We then print the original and encrypted messages to the console.

To demonstrate decryption, we reinitialize the Cipher to DECRYPT_MODE with the same secret key and decrypt the encrypted message. Finally, we print the decrypted message to the console.

The encrypted message will vary each time you run the program, due to the unique secret key generated each time.

The important thing to note here is that the decrypted message is identical to the original message, demonstrating that our encryption and decryption process is working correctly.

Points to Remember

Symmetric encryption is a powerful tool for maintaining confidentiality, but it's important to remember that the security of your data depends on the security of your key. If an unauthorized person gains access to your secret key, they can decrypt your data. Therefore, it's crucial to keep your secret keys secure.

Conclusion

Implementing symmetric encryption in Java is a straightforward process thanks to the javax.crypto package. Understanding how to use the Cipher and KeyGenerator classes to encrypt and decrypt data can provide a significant boost to the security of your Java applications.

Updated on: 15-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements