1. Home
  2. Virtual Card Management
  3. JAVA AES Example

JAVA AES Example

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.Validation;
import javax.validation.Validator;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Base64;
import static java.nio.charset.StandardCharsets.UTF_8;



public class EncryptionService {

    private String encrypt(String data, String iv, String key) {
        try {
            Cipher _Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            byte[] _iv = iv.getBytes();
            IvParameterSpec ivspec = new IvParameterSpec(_iv);
            Key SecretKey = new SecretKeySpec(key.getBytes(),
            "AES");
            _Cipher.init(Cipher.ENCRYPT_MODE, SecretKey, ivspec);
            return org.apache.commons.codec.binary.Base64.encodeBase64String(_Cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            System.out.println("Error while attempting to encrypt using iv and key");
        }
    }

    private String decrypt(String data, String iv, String key) {
        try
        {
            Cipher _Cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            byte[] _iv = iv.getBytes();
            IvParameterSpec ivspec = new IvParameterSpec(_iv);
            Key SecretKey = new SecretKeySpec(key.getBytes(),
            "AES");
            _Cipher.init(Cipher.DECRYPT_MODE, SecretKey, ivspec);
            return new String(_Cipher.doFinal(org.apache.commons.codec.binary.Base64.decodeBase64(data)));
        } catch (Exception e) {
            System.out.println("Error while attempting to decrypt using iv and key");
        }
    }
}

Was this article helpful to you? Yes No

How can we help?