package com.chenyang.nse.bussiness.odbc.business;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.chenyang.nse.bussiness.odbc.po.Sm4Info;
import com.chenyang.nse.bussiness.odbc.po.Sm4Result;
import com.chenyang.nse.bussiness.tools.encryption.EncProvider;

public class Sm4Api implements OdbcApiCallable {
   public Object invoke(byte[] data) {
      ObjectMapper mapper = new ObjectMapper();
      Sm4Info info = null;
      Sm4Result result = new Sm4Result();

      try {
         info = (Sm4Info)mapper.readValue(data, Sm4Info.class);
         if (info.getData() != null && info.getData().length() != 0) {
            if (info.getType().equals("enc")) {
               result.setText(EncProvider.encryptEcb("SM4", info.getKey(), info.getData(), info.getLike(), info.getStart(), info.getEnd(), info.getTwoindex()));
            } else if (info.getType().equals("dec")) {
               result.setText(EncProvider.decryptEcb("SM4", info.getKey(), info.getData(), info.getLike(), info.getStart(), info.getEnd(), info.getTwoindex()));
            } else {
               result.setMessage("错误的加密解密动作:" + info.getType());
               result.setText(info.getData());
            }

            return result;
         } else {
            result.setText(info.getData());
            return result;
         }
      } catch (Exception e) {
         e.printStackTrace();
         if (data != null) {
            result.setText(info.getData());
         }

         result.setMessage("加密机密失败：" + e.getMessage());
         return data;
      }
   }
}
