package com.chenyang.nse.bussiness.controller;

import com.alibaba.fastjson.JSONObject;
import com.chenyang.nse.bussiness.service.engine.EngineOperateService;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/test"})
public class TestController {
   @Autowired
   private EngineOperateService service;

   @RequestMapping({"/main"})
   public void main(String id) {
      this.service.executeTask(id);
   }

   @ResponseBody
   @RequestMapping(
      method = {RequestMethod.GET},
      produces = {"text/json;charset=UTF-8"}
   )
   public String test2() {
      new HashMap();
      Map<Integer, String> keyMap = genKeyPair();
      System.out.println("随机生成的公钥为:" + (String)keyMap.get(0));
      System.out.println("随机生成的私钥为:" + (String)keyMap.get(1));
      String message = "随机生成的公钥为:" + (String)keyMap.get(0);
      message = JSONObject.toJSONString(message);
      return message;
   }

   public static Map genKeyPair() {
      Map<Integer, String> keyMap = new HashMap();

      try {
         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
         keyPairGen.initialize(3072, new SecureRandom());
         KeyPair keyPair = keyPairGen.generateKeyPair();
         RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
         RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
         String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
         String privateKeyString = new String(Base64.encodeBase64(privateKey.getEncoded()));
         keyMap.put(0, publicKeyString);
         keyMap.put(1, privateKeyString);
      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
      }

      return keyMap;
   }
}
