package com.pj.utils;


public enum Encoder implements EncoderInterface{
    Hex("Hex"),Base64("Base64");
    private String encoderName;
    Encoder(String name){
        encoderName = name;
    }

    @Override
    public String encode(byte[] input) {

        if ("Hex".equals(encoderName)){
            return hexEncode(input);
        }

        if ("Base64".equals(encoderName)){
            return base64Encode(input);
        }

        return null;
    }

    @Override
    public byte[] decode(String input) {
        if ("Hex".equals(encoderName)){
            return hexDecode(input);
        }

        if("Base64".equals(encoderName)){
            return base64Decode(input);
        }

        return null;
    }
    /*
    *
    * byte[] 转为hex字符串
    *
    * */
    private String hexEncode(byte[] bytes){
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim();
    }


    /*
    *
    *
    * hex字符串转byte[]
    *
    *
    * */
    private byte[] hexDecode(String hex){

        int m = 0, n = 0;
        int byteLen = hex.length() / 2; // 每两个字符描述一个字节
        byte[] ret = new byte[byteLen];
        for (int i = 0; i < byteLen; i++) {
            m = i * 2 + 1;
            n = m + 1;
            int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
            ret[i] = Byte.valueOf((byte)intVal);
        }
        return ret;
    }

    private boolean isEmpty(String hex) {
        return hex == null || "".equals(hex);
    }

    private String base64Encode(byte[] input){
        return java.util.Base64.getEncoder().encodeToString(input);
    }

    private byte[] base64Decode(String base64Str){
        return java.util.Base64.getDecoder().decode(base64Str);
    }






}
