Java AES encryption and decryption

Follow May 24, 2017 · 2 mins read

Introduction

In cryptography, encryption is the process of encoding a message or information in such a way that only authorized parties can access it

Encryption does not of itself prevent interference, but denies the intelligible content to a would-be interceptor

In an encryption scheme, the intended information or message, referred to as plaintext, is encrypted using an encryption algorithm, generating ciphertext that can only be read if decrypted.

For technical reasons, an encryption scheme usually uses a pseudo-random encryption key generated by an algorithm. It is in principle possible to decrypt the message without possessing the key, but, for a well-designed encryption scheme, considerable computational resources and skills are required.

An authorized recipient can easily decrypt the message with the key provided by the originator to recipients but not to unauthorized users.

Encryption Schemes

Efficient encryption schemes usually operate on fixed-size messages called blocks. Such schemes are called block ciphers.

Well-known examples:

  • DES (Data Encryption Standard).
  • 3DES (Triple DES)
  • AES (Advanced Encryption Standard)

AES

The Advanced Encryption Standard, or AES, is a symmetric block cipher.

It chosen by the U.S. government to protect classified information and is implemented in software and hardware throughout the world to encrypt sensitive data

In present day cryptography, AES is widely adopted and supported in both hardware and software.


import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

//Generate a key for encryption of specified length
    public static SecretKey getSecretEncryptionKey(int length) throws Exception{
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        System.out.println(generator.getProvider().toString());
        generator.init(length); // The AES key size in number of bits
        SecretKey secKey = generator.generateKey();
        return secKey;
    }

Once the key is generated we can encrypt any plain text using the secret key

    public String encryptText(String plainText,SecretKey SEC_KEY,String initVector) throws Exception{

        Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
       IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        aesCipher.init(Cipher.ENCRYPT_MODE, SEC_KEY,iv);
        byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
        String encryptedData = Base64.getEncoder().encodeToString(byteCipherText);

        return encryptedData;
    }

Any entity with the access to the secret key would be able to decrypt the encoded text message

    public String decryptText(String encryptedData,SecretKey SEC_KEY,String initVector) throws Exception {

        byte[] byteCipherText = Base64.getDecoder().decode(encryptedData);
				IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
        Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        aesCipher.init(Cipher.DECRYPT_MODE, SEC_KEY,iv);
        byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
        return new String(bytePlainText);
    }

The following functions allow us to encrypt a AES 128 bit key and encode and decode a string using CBC block cipher algorithm and use PKCS5Padding scheme

One of best-known, good block cipher modes is cipher block chaining (CBC).With it, every ciphertext block depends on all previous ciphertext blocks, which avoids repetition problems like we observed with ECB.

           String plaintext="12345asdasdadsadasd";					 
            String initVector = "RandomInitVector"; // 16 bytes IV
            SecretKey k=getSecretEncryptionKey(128);
            String e=encryptText(plaintext, k,initVector);
            String d=decryptText(e, k,initVector);
            System.out.println("AES encryption Testing -> text "+plaintext+"\n Encrypted String : "+e+"\n Descrypted String "+d);

References

  • http://www.cs.cornell.edu/courses/cs5430/2015sp/notes/crypto.php
Written by