AES - Using Advanced Encryption Standard in Java

Submitted by Karthikeyan on

A simple java program that uses AES Encryption Method


import java.io.*;
import java.security.*;
import javax.crypto.*;
import java.util.*;
public class AES {
    public static void main(String args[])
    {
        try
        {
            Cipher aesCipher = Cipher.getInstance("AES");
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom randomSeed = new SecureRandom();
            keygen.init(randomSeed);
            Key aeskey = keygen.generateKey();
            int mode = Cipher.ENCRYPT_MODE;
            aesCipher.init(mode, aeskey);
            Scanner console = new Scanner(System.in);
            System.out.println("Enter a text for encryption");
            String plainText = console.nextLine();
            String encryptedText = crypt(aesCipher,plainText);
            System.out.println("The encrypted text is " +encryptedText);
            mode = Cipher.DECRYPT_MODE;
            aesCipher.init(mode, aeskey);
            String decryptedText = crypt(aesCipher,encryptedText);
            System.out.println("The decrypted text is "+decryptedText);
            
        }
        catch(GeneralSecurityException e)
                {
                    System.out.println("Security Exception :"+ e.getMessage());
                }
    }
    
    public static String crypt(Cipher aesCipher, String in) throws GeneralSecurityException
    {
        int inSize = aesCipher.getBlockSize();
        byte[] inBytes = new byte[inSize];
        inBytes = in.getBytes();
        int outSize = aesCipher.getOutputSize(inSize);
        byte[] outBytes = new byte[outSize];
        outBytes = aesCipher.doFinal(inBytes);
        String out = new String(outBytes);
        return out;
                
    }
}