example code encrypt and decrypt with java

java

Here is an example of how to encrypt and decrypt a message using the Java Cryptography Extension (JCE):

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    public static void main(String[] args) throws Exception {
        // Set up secret key and cipher
        SecretKey secretKey = new SecretKeySpec("mysecretkey".getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // Encrypt the message
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encrypted = cipher.doFinal("Hello, World!".getBytes());
        System.out.println("Encrypted message: " + new String(encrypted));

        // Decrypt the message
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(cipher.getIV()));
        byte[] decrypted = cipher.doFinal(encrypted);
        System.out.println("Decrypted message: " + new String(decrypted));
    }
}

This code uses the AES (Advanced Encryption Standard) algorithm in Cipher Block Chaining (CBC) mode with PKCS5 padding. The secret key is specified as a string, but in a real application it should be generated using a secure random number generator and stored in a secure location.

The Cipher.getInstance() method is used to create a Cipher object that implements the specified transformation. The transformation string consists of the name of the algorithm (AES), the block cipher mode (CBC), and the padding scheme ( PKCS5Padding).

The cipher.init() method is used to initialize the Cipher object for either encryption or decryption. The Cipher.ENCRYPT_MODE and Cipher.DECRYPT_MODE constants are used to specify the operation. The secretKey and IvParameterSpec objects are used to specify the secret key and initialization vector (IV) for the operation, respectively.

The cipher.doFinal() method is used to perform the actual encryption or decryption. It takes as input the message to be encrypted or decrypted, and returns the encrypted or decrypted message as a byte array.