rsa 生成密匙 ,密匙导出,加密解密封装

利用hutool实现,原谅我只是个调参侠!

RSA工具类




import cn.hutool.core.io.file.FileReader;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.util.ResourceUtils;


public class RSAUtil {
    private static RSA rsa = null;

    static {
        try {
            FileReader fileReader = new FileReader(ResourceUtils.getFile("classpath:publickey.pem"));
            String publicKeyStr = fileReader.readString();

            FileReader fileReaderPrivate = new FileReader(ResourceUtils.getFile("classpath:privatekey.pem"));
            String privateKeyStr = fileReaderPrivate.readString();
            rsa = new RSA(privateKeyStr, publicKeyStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解密
     *
     * @param data
     * @return
     */
    public static String decrypt(String data) {
        return rsa.decryptStr(data, KeyType.PrivateKey);
    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encrypt(String data) {

        return rsa.encryptHex(data, KeyType.PublicKey);
    }


}

密匙导出 junit

  @Test
    public void exportKeys() throws IOException {

        RSA rsa = new RSA();
//获得私钥
        rsa.getPrivateKey();
        rsa.getPrivateKeyBase64();
//获得公钥
        rsa.getPublicKey();
        rsa.getPublicKeyBase64();

        FileWriter writer = new FileWriter("d:/publickey.pem");
        writer.write(rsa.getPublicKeyBase64());

        FileWriter writer1 = new FileWriter("d:/privatekey.pem");
        writer1.write(  rsa.getPrivateKeyBase64());
    }

    @Test
    public void testDecryptEncrypt() throws IOException {
        String en = RSAUtil.encrypt("程序员123");
        LOGGER.info(en);
        String de =  RSAUtil.decrypt(en);
        LOGGER.info(de);
        Assert.assertEquals("程序员123", de);

    }
有理想的coder CSDN认证博客专家 全栈工程师 终生学习者 懂营销的程序猿
坐标郑州,从业经验10余年,擅长javaweb技术栈,实战经验丰富。目前感兴趣方向:打造副业,网络安全,高可用高并发,架构,营销。更多干货请关注微信公众号lovepythoncn,关注我交个朋友!
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页