package cokr.xit.ens.core.utils.crypto;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

@Slf4j
public class AES256 {
    private String scretKey;
    private String iv;
    private Key keySpec;


    public AES256(String key) {
        this.scretKey = key.substring(0, 32);
        this.iv = key.substring(0, 16);
        byte[] keyBytes = new byte[16];
        try {
            byte[] b = scretKey.getBytes("UTF-8");
            int len = b.length;
            if (len > keyBytes.length) {
                len = keyBytes.length;
            }
            System.arraycopy(b, 0, keyBytes, 0, len);
        } catch (Exception e) {
            e.printStackTrace();
        }
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");

        this.keySpec = keySpec;

    }

    public String encrypt(String str) {
        if (str == null || "".equals(str)) return str;
        try {
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
            c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));

            byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
            String encStr = new String(Base64.encodeBase64(encrypted));
            return encStr;

        } catch (Exception e) {
            log.error("AES encode fail. {}", e.getMessage());
            e.printStackTrace();
            return str;
        }
    }

    public String decrypt(String str) {
        if (str == null || "".equals(str)) return str;
        try {
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
            c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));
            byte[] byteStr = Base64.decodeBase64(str.getBytes());
            String decStr = new String(c.doFinal(byteStr), "UTF-8");
            return decStr;

        } catch (Exception e) {
            log.error("AES decode fail. {}", e.getMessage());
            e.printStackTrace();
            return str;
        }
    }
}
