AES Encryption with Source Code – JavaFX

AES

Hi guys today we’re gonna teach you about AES-Encryption. This encryption method is very useful for protecting your data against any intrusion. Even if intruders may gain access on your data, they still cant understand them because they are all encrypted.

Some curiosities:

AES was developed by two belgian cryptographers. This encryption method was first used by United States government and a lot of other governments started using it afterwards. AES this encryption is used on each router that we use today to encrypt the Wi-Fi passwords! Surely you’ve noticed http and https at the URL of websites. Both are transfer protocols but guess what? Https is encrypted with RSA which is another encrypting method like AES. We will explain more about RSA in future.

We will provide you the source code of a simple AES application I created with JavaFX, which will help you encrypt/decrypt your data.

So first you are going to need a key and an init vector. Let’s suppose the key and the init vector have the following values :

String key = "Jar12345Jar12345";
String initVector = "RandomInitVector";

 

Then you need 2 methods :

1-the encrypt method

public static String encrypt(String key, String initVector, String value)
  {
    try {
      IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
      SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
      
      Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5PADDING");
      cipher.init(1, skeySpec, iv);
      
      byte[] encrypted = cipher.doFinal(value.getBytes());
      
      return Base64.encodeBase64String(encrypted);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    
    return null;
  }

 

2-the decrypt method

 public static String decrypt(String key, String initVector, String encrypted) {
     try {
       IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
       SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
       
       Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5PADDING");
       cipher.init(2, skeySpec, iv);
       
       byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
       
       return new String(original);
     } catch (Exception ex) {
       Alert a = new Alert(AlertType.ERROR, "Input length must be multiple of 16", 
                        ButtonType.CANCEL);
       a.show();
     }
     
     return null;
   }

 

These 2 methods are the “key” methods in our program. I wont go into details of how the application is build in JavaFX. Here is a photo of the program.

 

AES Encryption Software

Below is the source code.

AES Encryption

Enjoy, thank you!

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here