package com.crm.rely.backend.util;

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

public class DESedeUtil {
    private static final String ENCODING_UTF_8 = "utf8";
    private static final String DESEDE_ALGORITHM = "DESede";
    private static final String DESEDE_CBC_PKCS5PEADDING_ALGORITHM = "DESede/CBC/PKCS5Padding";
    public static String encrypt(String message, String secretKey) throws Exception {

        return encrypt(message, secretKey, ENCODING_UTF_8);
    }

    public static String encrypt(String message, String secretKey, String encoding) throws Exception {
        byte[] secretKeyBytes = secretKey.getBytes(encoding);
        byte[] keyBytes = secretKey.substring(0, 8).getBytes(encoding);
        final SecretKey key = new SecretKeySpec(secretKeyBytes, DESEDE_ALGORITHM);
        final IvParameterSpec iv = new IvParameterSpec(keyBytes);
        final Cipher cipher = Cipher.getInstance(DESEDE_CBC_PKCS5PEADDING_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        final byte[] plainTextBytes = message.getBytes(encoding);
        final byte[] cipherText = cipher.doFinal(plainTextBytes);
        return bytes2HexString(cipherText);
    }

    public static String bytes2HexString(byte[] b) {
        byte[] hex = "0123456789ABCDEF".getBytes();
        byte[] buff = new byte[2 * b.length];
        for (int i = 0; i < b.length; i++) {
            buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
            buff[2 * i + 1] = hex[b[i] & 0x0f];
        }
        return new String(buff);
    }

    public static byte[] hexStringToBytes(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static String decrypt(String message, String secretKey) throws Exception {

        return decrypt(message, secretKey, ENCODING_UTF_8);
    }

    public static String decrypt(String message, String secretKey, String encoding) throws Exception {
        byte[] messageBytes = hexStringToBytes(message);
        byte[] secretKeyBytes = secretKey.getBytes(encoding);
        byte[] keyBytes = secretKey.substring(0, 8).getBytes(encoding);
        final SecretKey key = new SecretKeySpec(secretKeyBytes, DESEDE_ALGORITHM);
        final IvParameterSpec iv = new IvParameterSpec(keyBytes);
        final Cipher decipher = Cipher.getInstance(DESEDE_CBC_PKCS5PEADDING_ALGORITHM);
        decipher.init(Cipher.DECRYPT_MODE, key, iv);
        final byte[] plainText = decipher.doFinal(messageBytes);
        return new String(plainText, encoding);
    }

}
