Java RSA Util

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA工具类
 * <a href="https://hutool.cn/docs/#/crypto/%E9%9D%9E%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86-AsymmetricCrypto">
 * hutool工具类封装
 * </a>
 */
public class RSAUtil {

    /**
     * 生成公私钥对
     */
    public static Map<String, String> generateKeyPairs() {
        RSA rsa = new RSA();
        Map<String, String> map = new HashMap<>();
        map.put("privateKey", rsa.getPrivateKeyBase64());
        map.put("publicKey", rsa.getPublicKeyBase64());
        return map;
    }

    /**
     * 加密
     *
     * @param publicKey 公钥
     * @param plain     明文
     */
    public static String encrypt(String publicKey, String plain) {
        RSA rsa = new RSA(null, publicKey);
        byte[] cipher = rsa.encrypt(plain.getBytes(StandardCharsets.UTF_8), KeyType.PublicKey);
        return Base64.encode(cipher);
    }

    /**
     * 解密
     *
     * @param privateKey 私钥
     * @param cipher     密文
     */
    public static String decrypt(String privateKey, String cipher) {
        RSA rsa = new RSA(privateKey, null);
        byte[] plain = rsa.decrypt(Base64.decode(cipher), KeyType.PrivateKey);
        return new String(plain, StandardCharsets.UTF_8);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值