package com.xjrsoft.common.utils;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.security.KeyPair;
import java.util.Base64;

public class RSAUtilTest {
    @Test
    public void TestRSAUtil(){
        try {

            ClassPathResource classPathResource = new ClassPathResource("rsa_private_key.pem");
            InputStream priIS =classPathResource.getInputStream();

            classPathResource = new ClassPathResource("rsa_public_key.pem");
            InputStream pubIS =classPathResource.getInputStream();


//            String privateKey = new String(IOUtils.toByteArray(priIS));
            String publicKey = new String(IOUtils.toByteArray(pubIS));

            // 生成密钥对
//            KeyPair keyPair = RSAUtil.getKeyPair();
//
//            String privateKey = new String(Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
//            String publicKey = new String(Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));

//            System.out.println("私钥:" + privateKey);
            System.out.println("公钥:" + publicKey);

            // RSA加密
            String data = "asdfasdfasdfasdfasdfa";
            String encryptData = RSAUtil.encrypt(data, RSAUtil.getPublicKey(publicKey));
            System.out.println("加密后内容:" + encryptData);
            // RSA解密
            String decryptData = RSAUtil.decrypt(encryptData);
            System.out.println("解密后内容:" + decryptData);
            // RSA签名
//            String sign = RSAUtil.sign(data, RSAUtil.getPrivateKey(privateKey));
//            // RSA验签
//            boolean result = RSAUtil.verify(data, RSAUtil.getPublicKey(publicKey), sign);
//            System.out.println("验签结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("RSA加解密异常");
        }
    }

    @Test
    public void TestGenRSA() throws Exception {
        RSAUtil.generateKeyPairResources();
    }
}
