Encrypt and Decrypt String in Java using AES Algorithm

 

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
public class Helper {
 
    private static final String SECRET_KEY = "qazy~!@#0987GYHN";  
 
    // Encrypts a string using AES algorithm
    public static String encryptString(String plainText) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
 
    // Decrypts a string using AES algorithm
    public static String decryptString(String encryptedText) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
 
 
}
 

Note: The AES algorithm requires a valid key length of 128, 192, or 256 bits, 
which corresponds to 16, 24, or 32 bytes respectively. 
In the example code provided, the SECRET_KEY is set to "qazy~!@#0987GYHN", 
which is 16 bytes or 128 bits in length.


Comments