How do you use Cipher with a simple code example?

The Java Cipher class provides the functionality of a cryptographic cipher for data encryption and decryption. It's a part of the Java Cryptography Architecture (JCA) and allows you to perform block and stream encryption using various algorithms such as AES, DES, etc.

Java Cipher Example

Below is a simple example of how to use the Cipher class to encrypt and decrypt data using AES algorithm:

import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class CipherExample { public static void main(String[] args) throws Exception { // Generate a key KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); // for AES-128 SecretKey secretKey = keyGen.generateKey(); // Create Cipher instance Cipher cipher = Cipher.getInstance("AES"); // Encrypt cipher.init(Cipher.ENCRYPT_MODE, secretKey); String originalText = "Hello, World!"; byte[] encryptedBytes = cipher.doFinal(originalText.getBytes()); // Decrypt cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); String decryptedText = new String(decryptedBytes); System.out.println("Original: " + originalText); System.out.println("Decrypted: " + decryptedText); } }

Java Cryptography Cipher Data Encryption AES DES Java Programming