package com.gem.media.splash.base.crash;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AesUtils {

    private static final String AES = "AES";
    private static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";

    public static byte[] encryptString(String key, String iv, String cleartext)
            throws Exception {
        return encryptByte(key, iv, cleartext.getBytes("utf-8"));
    }

    public static byte[] decryptByte(String key, String iv, byte[] encrypted)
            throws Exception {
        Cipher cipher = initAESCipher(key, iv, Cipher.DECRYPT_MODE);
        return cipher.doFinal(encrypted);
    }

    public static byte[] encryptByte(String key, String iv, byte[] clear)
            throws Exception {
        Cipher cipher = initAESCipher(key, iv, Cipher.ENCRYPT_MODE);
        return cipher.doFinal(clear);
    }

    public static Cipher initAESCipher(String key, String iv, int cipherMode)
            throws Exception {
        IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes("utf-8"));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("utf-8"), AES);
        Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING);
        cipher.init(cipherMode, skeySpec, zeroIv);
        return cipher;
    }
}
