package com.dkl.web.util;

import com.koal.kms.sdk.ed.KmsSdkException;
import com.koal.kms.sdk.ed.KmsUtil;
import com.koal.kms.sdk.ed.Mode;
import com.dkl.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class EnciphermentUtil {
    public static final Logger log = LoggerFactory.getLogger(EnciphermentUtil.class);
    public static void main(String[] args) throws KmsSdkException {
        kmsEncrypt("测试加密");
    }
    /**
     * 数据加密
     * originData 待加密数据
     */
    public static String kmsEncrypt(  String originData) throws KmsSdkException {
        log.info("原始数据={}",originData);
        byte[] encryptData = KmsUtil.encrypt(originData.getBytes(), Mode.CBC);
        // 若要保存密文，使用Base64做编码处理
        String saveEncryptData = Base64.getEncoder().encodeToString(encryptData);
        log.info("加密数据={}",saveEncryptData);
        return saveEncryptData;
    }

    /**
     * 数据解密
     * encryptData 加密后的数据
     */

    public static String kmsDencrypt(String encryptData) throws KmsSdkException {
        log.info("加密数据={}",encryptData);
        // 解密前使用Base64做解码处理
        byte[] decryptData = Base64.getDecoder().decode(encryptData);
        byte[] decryptResult = KmsUtil.decrypt(decryptData, Mode.CBC);
        String result=new String(decryptResult);
        log.info("解密后={}",result);
        return result;
    }
}
