package com.sf.sdk.demo.safety;

import android.util.Base64;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

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

/**
 * AES
 */
public class AES {

    private static final Charset UTF_8 = StandardCharsets.UTF_8;
    private static final String AES_ALGORITHM = "AES";
    private static final String AES_TRANSFORMATION = "AES/CBC/PKCS5Padding";

    public static String encrypt(String key, String iv, String data) {
        byte[] bytes = doCipher(key, iv, data.getBytes(UTF_8), Cipher.ENCRYPT_MODE);
        if (bytes != null) {
            return new String(Base64.encode(bytes, Base64.NO_WRAP), UTF_8);
        }
        return null;
    }

    public static String decrypt(String key, String iv, String data) {
        byte[] bytes = doCipher(key, iv, Base64.decode(data.getBytes(UTF_8), Base64.NO_WRAP), Cipher.DECRYPT_MODE);
        return bytes == null ? null : new String(bytes, UTF_8);
    }

    private static byte[] doCipher(String key, String iv, byte[] bytes, int opmode) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(UTF_8), AES_ALGORITHM);
            Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(UTF_8));
            cipher.init(opmode, secretKeySpec, ivParameterSpec);
            return cipher.doFinal(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
