package org.springblade.activity.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;
import java.util.Base64;

@Slf4j
public class EnDecHelper2 {

    private static final String ECB_MOB = "DES/ECB/PKCS5Padding";
    private static final String CHAESET_NAME = "UTF-8";
    private static final String SECRET_KEY_TYPE = "DES";

    public static String channel = "kechuang";
    public static String pwd = "!QAW2djxns";

    public static String encode(String data) throws Exception {
        Cipher enCipher = Cipher.getInstance(ECB_MOB);
        Key key = getKey(pwd);
        enCipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] pasByte = enCipher.doFinal(data.getBytes(CHAESET_NAME));
        return Base64.getEncoder().encodeToString(pasByte);
    }

    //for vip sms
    public static String encodeByPwd(String data,String pwd) throws Exception {
        Cipher enCipher = Cipher.getInstance(ECB_MOB);
        Key key = getKey(pwd);
        enCipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] pasByte = enCipher.doFinal(data.getBytes(CHAESET_NAME));
        return Base64.getEncoder().encodeToString(pasByte);
    }

    private static Key getKey(String password) throws Exception {
        byte[] DESkey = password.getBytes(CHAESET_NAME);
        DESKeySpec keySpec = new DESKeySpec(DESkey);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_KEY_TYPE);
        return keyFactory.generateSecret(keySpec);
    }

    public static String decode(String data) {
        try {
            Cipher deCipher = Cipher.getInstance(ECB_MOB);
            Key key = getKey(pwd);
            deCipher.init(Cipher.DECRYPT_MODE, key);
            byte[] pasByte = deCipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHAESET_NAME)));
            return new String(pasByte, CHAESET_NAME);
        } catch (Exception e) {
            log.info("decode异常: {}", e.getMessage());
            return "";
        }

    }

    public static String decodeWithPwd(String data, String password) {
        try {
            Cipher deCipher = Cipher.getInstance(ECB_MOB);
            Key key = getKey(password);
            deCipher.init(Cipher.DECRYPT_MODE, key);
            byte[] pasByte = deCipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHAESET_NAME)));
            return new String(pasByte, CHAESET_NAME);
        } catch (Exception e) {
            log.info("decode异常: {}", e.getMessage());
            return "";
        }

    }
}
