package com.ruoyi;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.web.work.domain.Notice;
import com.ruoyi.web.work.domain.Relate;
import com.ruoyi.web.work.service.INoticeService;
import com.ruoyi.web.work.service.IRelateService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RuoYiApplication.class)
public class user {

    @Autowired
    private IRelateService relateService;

    @Autowired
    private INoticeService noticeService;

    @Test
    @Transactional
    public void aa() {
        Relate relate = new Relate();
        relateService.updateById(relate);

        Notice notice = new Notice();
        notice.setTitle("高韦神");
        notice.setState(0);
        notice.setContents("高韦神");
        noticeService.save(notice);

        System.out.println("操作成功");
    }

    @Test
    public void tt() {
        String host = "https://cardnumber.market.alicloudapi.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "afda0d1b5d984f3bad99a2b362ec9285";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        // 对图像进行base64编码
        String imgBase64 = "http://123.60.57.26/api/profile/upload/2024/04/22/1713726675590.jpg";
        //configure配置
        JSONObject configObj = new JSONObject();
        configObj.put("side", "face");
        String config_str = configObj.toString();
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        if (configObj.size() > 0) {
            requestObj.put("configure", config_str);
        }
        String bodys = requestObj.toString();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                return;
            }
            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            System.out.println(res_obj.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 初始化密钥生成器
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        // 设置密钥长度，可以根据需要调整
        keyGen.initialize(2048);

        // 生成密钥对
        KeyPair pair = keyGen.genKeyPair();
        PrivateKey privateKey = pair.getPrivate();
        PublicKey publicKey = pair.getPublic();

        // 将私钥转换为Base64编码的字符串
        String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        System.out.println("Private Key (Base64):");
        System.out.println(privateKeyString);

        // 将公钥转换为Base64编码的字符串
        String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        System.out.println("Public Key (Base64):");
        System.out.println(publicKeyString);
    }
    public static String generatePrivateKeyAsString() throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 初始化密钥生成器
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048); // 可以根据需要调整密钥长度

        // 生成密钥对
        KeyPair pair = keyGen.genKeyPair();
        PrivateKey privateKey = pair.getPrivate();

        // 将私钥转换为PKCS#8编码的字节数组
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey pkcs8PrivateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        // 将私钥编码为Base64字符串
        byte[] encoded = pkcs8PrivateKey.getEncoded();
        String base64EncodedPrivateKey = Base64.getEncoder().encodeToString(encoded);

        return base64EncodedPrivateKey;
    }

    public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA"); // 通常需要指定填充模式，如 "RSA/ECB/PKCS1Padding"
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.getDecoder().decode(text));
        return new String(result); // 注意：这里假设密文是文本且使用UTF-8编码，如果不是，需要相应地处理
    }
}
