Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of AES encryption and decryption in Java
/**
* Code written by P. Gajland
* https://github.com/GaPhil
*
* IMPORTANT:
* This code is for educational and demonstrative purpose only.
* If you need to do serious encryption for "production" it is
* recommended to investigate more traditional libraries and
* gain some specific knowledge on cryptography and security.
*/
import java.security.Key;
import javax.crypto.Cipher;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import javax.crypto.spec.SecretKeySpec;
public class AESenc {
private static final String ALGO = "AES";
private static final byte[] keyValue =
new byte[]{'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
/**
* Encrypt a string with AES algorithm.
*
* @param data is a string
* @return the encrypted string
*/
public static String encrypt(String data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(data.getBytes());
return new BASE64Encoder().encode(encVal);
}
/**
* Decrypt a string with AES algorithm.
*
* @param encryptedData is a string
* @return the decrypted string
*/
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
return new String(decValue);
}
/**
* Generate a new encryption key.
*/
private static Key generateKey() throws Exception {
return new SecretKeySpec(keyValue, ALGO);
}
}
@marlonlom

This comment has been minimized.

Copy link

@marlonlom marlonlom commented Sep 20, 2017

The compiler display warnings if you use Sun's proprietary Java classes. I'm of the opinion that it's generally a bad idea to use these classes. read > https://stackoverflow.com/questions/1834826/it-is-a-bad-practice-to-use-suns-proprietary-java-classes

@iamprashant

This comment has been minimized.

Copy link

@iamprashant iamprashant commented Sep 27, 2017

Remove import from sun.*

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESenc {
  private static final String ALGO = "AES";
  private static final byte[] keyValue =
            new byte[]{'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};

    /**
     * Encrypt a string with AES algorithm.
     *
     * @param data is a string
     * @return the encrypted string
     */
    public static String encrypt(String data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encVal);
    }

    /**
     * Decrypt a string with AES algorithm.
     *
     * @param encryptedData is a string
     * @return the decrypted string
     */
    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = Base64.getDecoder().decode(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        return new String(decValue);
    }

    /**
     * Generate a new encryption key.
     */
    private static Key generateKey() throws Exception {
        return new SecretKeySpec(keyValue, ALGO);
    }

}
@merugu

This comment has been minimized.

Copy link

@merugu merugu commented Mar 23, 2018

Hi,

I'm trying similar kind of Decryption and getting "Illegal key size or default parameters" exception.
My key size is "32 characters".

@adminmichael

This comment has been minimized.

Copy link

@adminmichael adminmichael commented Mar 25, 2018

what application we need

@RZMiRaN

This comment has been minimized.

Copy link

@RZMiRaN RZMiRaN commented Apr 28, 2018

@merugu
it must be 16 characters length because each character is 8 bits, which means 16 characters will make 128 bits

@cristianprofile

This comment has been minimized.

Copy link

@cristianprofile cristianprofile commented Nov 15, 2018

10000 thanks for your code!!!!! It works like a charm!!!!!

@SuganV

This comment has been minimized.

Copy link

@SuganV SuganV commented Nov 26, 2018

Isnt it possible to have keyValue byte in a String Datatype ???

@aayush9333

This comment has been minimized.

Copy link

@aayush9333 aayush9333 commented Feb 23, 2019

What will be the main class?

@ahmedalfakih97

This comment has been minimized.

Copy link

@ahmedalfakih97 ahmedalfakih97 commented Mar 1, 2019

dosn't hava a main method

@Uyagi

This comment has been minimized.

Copy link

@Uyagi Uyagi commented Mar 15, 2019

What will be the main class?

Added what would make a potential main method work

import java.util.Scanner;


public class AESenc {

    private static Scanner input = new Scanner(System.in);
    private static String data = input.nextLine();


    /** 
     * Main
     */
    public static void main(String[] args) throws Exception
    { 
        AESenc cipher = new AESenc();
        System.out.println(cipher.encrypt(data));
    } 

}

@networkspyghana

This comment has been minimized.

Copy link

@networkspyghana networkspyghana commented Apr 2, 2019

please how can i convert this code to php. i want to encrypte with php and decrypt with java

@ApoorvaOjha

This comment has been minimized.

Copy link

@ApoorvaOjha ApoorvaOjha commented Jun 14, 2020

I am getting this exception when I run the same code in decryption process... please help!

Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:934)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:845)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at ae1.Ae1.decrypt(Ae1.java:40)
at ae1.Ae1.main(Ae1.java:60)
C:\Users\apoor\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment