RSA加解密工具类 - RSAUtils

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;


public class RsaUtil {
    // 公钥
    private static final String publicKey = "";
    // 秘钥
    private static final String privateKey = "";

    /**
     * 加密字符串
     */
    public static String encrypt(String data) {
        if (data == null || data.isEmpty()) {
            return data;
        }
        byte[] infoBytes = data.getBytes(StandardCharsets.UTF_8);
        byte[] encrypt = encrypt(publicKey, infoBytes);
        return Base64.getEncoder().encodeToString(encrypt);
    }

    /**
     * 解密字符串
     */
    public static String decrypt(String data) {
        if (data == null || data.isEmpty()) {
            return data;
        }
        byte[] decode = Base64.getDecoder().decode(data);
        byte[] decrypt = decrypt(privateKey, decode);
        return new String(decrypt, StandardCharsets.UTF_8);
    }

    public static byte[] encrypt(String publicKey, byte[] srcBytes) {
        try {
            if (publicKey != null) {
                byte[] decode = Base64.getDecoder().decode(publicKey);
                RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decode));
                Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
                cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
                return cipher.doFinal(srcBytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] decrypt(String privateKey, byte[] srcBytes) {
        try {
            if (privateKey != null) {
                byte[] decode = Base64.getDecoder().decode(privateKey);
                RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decode));
                Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
                cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
                return cipher.doFinal(srcBytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
}
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值