How to use Encryption – Decryption in Java?

The Java platform strongly emphasizes security, including language safety, cryptography, public key infrastructure, authentication, secure communication, and access control.

The following example demonstrates the use of Java Programming language to implement encryption and decryption functionality.

e.g.: Java’s support for cryptography and security.

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;

class EncDec {

  
    /**
     * Encryption and Decryption is performed with the help of Cipher class. e.g. RSA, DES (Algorithms)
     * AES-Advanced Encryption Standard - Preferred
     * Symmetric Cipher - Keys are same
     * Asymmetric Cipher - Diff. Public and Private Keys
     * Cipher Modes: Encrypt, Decrypt, Wrap, UnWrap Mode
     * Cipher Category: Block and Stream Cipher
     * Note: - When Cipher is initialized it looses its identity
     *       - In Symmetric Cipher Key Generator class is used for generating cypher.
     */
    private static Key key=null;
    private static Cipher cipher=null;
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String algorithm=args[0];
        KeyGenerator keygen= KeyGenerator.getInstance(algorithm);
        key=keygen.generateKey();
        cipher=Cipher.getInstance(algorithm);
        byte[] encryptionBytes=null;
        String input=args[1];
        System.out.println("Enterered String: "+input);
        encryptionBytes=encrypt(input);
        System.out.println("Encrypted: "+new String(encryptionBytes));
        System.out.println("Recovered: "+decrypt(encryptionBytes));  
    }
    private static byte[] encrypt(String input) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] inBs=input.getBytes();
        return cipher.doFinal(inBs);
    }
    private static String decrypt(byte[] enBs) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] recoveredBytes=cipher.doFinal(enBs);
        String reccovered=new String(recoveredBytes);
        return reccovered;
    }
}

OUTPUT:
Encryption - Decryption