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);

    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员石磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值