Encryption and Decryption in java

Encryption and Decryption in Java Using AES with Example

Encryption and Decryption in Java

In this tutorial, you will learn how to perform encryption and decryption in Java using the AES algorithm. Java provides built-in support for AES through the javax.crypto package, so no external library is required.

The example below uses SecretKeySpec to create a 128-bit key and Cipher to encrypt and decrypt a string. The same key is used for both operations because AES is a symmetric encryption algorithm.

Java Source Code

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Demo {

    private SecretKey sk;

    private String mykey = "hellodeepsingh12"; // 16 bytes = 128-bit key

    public Demo() {

        try {

            // sk = KeyGenerator.getInstance("AES").generateKey();

            sk = new SecretKeySpec(mykey.getBytes(), "AES");

        } catch (Exception e) {

            System.out.println(e);

        }

    }

    private byte[] encrypt(String name) {

        byte[] cipherText = {};

        try {

            Cipher c = Cipher.getInstance("AES");

            c.init(Cipher.ENCRYPT_MODE, sk);

            byte[] input = name.getBytes();

            cipherText = c.doFinal(input);

            System.out.println(new String(cipherText));

        } catch (Exception e) {

            System.out.println(e);

        }

        return cipherText;

    }

    private void decrypt(byte[] data) {

        try {

            Cipher c1 = Cipher.getInstance("AES");

            c1.init(Cipher.DECRYPT_MODE, sk);

            byte[] dcipheredText = c1.doFinal(data);

            System.out.println(new String(dcipheredText));

        } catch (Exception e) {

            System.out.println(e);

        }

    }

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException,
              InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

        Demo d = new Demo();

        byte b[] = d.encrypt("this is my password");

        d.decrypt(b);

    }

}

Output

İ4k²Âbš_á ÔèR·ã«êæ?³Ъӌ
this is my password

The first line is the raw AES ciphertext printed with new String(cipherText), which is why it looks garbled. The second line shows the original plaintext after decryption.

Tip: To display the ciphertext as readable text, encode it with Base64.getEncoder().encodeToString(cipherText) and decode it before decryption.

Frequently Asked Questions

What is AES encryption in Java?

AES (Advanced Encryption Standard) is a symmetric encryption algorithm supported by Java through the javax.crypto package. It uses the same secret key for both encryption and decryption.

Why must an AES key be 16, 24, or 32 bytes?

AES supports key sizes of 128, 192, and 256 bits, which correspond to 16, 24, and 32 bytes respectively. Using a key with an invalid length throws InvalidKeyException.

Why is AES/ECB/PKCS5Padding recommended over plain AES?

Using just Cipher.getInstance("AES") relies on the provider default, which is usually AES/ECB/PKCS5Padding. Explicitly specifying the transformation makes the code portable and predictable across JVMs.

Why does the encrypted output look like random characters?

AES produces binary ciphertext, not printable text. Printing it with new String(cipherText) shows garbled characters because the bytes are not valid text. Encode it with Base64 to display it safely.

Conclusion

In this tutorial, you learned how to perform encryption and decryption in Java using the AES algorithm. You created a 128-bit SecretKeySpec, encrypted a string with Cipher.ENCRYPT_MODE, and decrypted it back with Cipher.DECRYPT_MODE.

Related topics: Java Cryptography, AES Encryption, Cipher Class, SecretKeySpec, Base64 Encoding Java, Java Security Tutorial

No comments: