RSA加密解密 JDK8实现

这是一个Java实现的RSA加解密工具类,使用JDK8的API,包括公钥加密和私钥解密的功能,同时涉及Base64编码和解码。类中包含了公钥和私钥的生成,以及对应的加密和解密方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RSA加密解密 JDK8实现

RSA

最近学习了一下RSA加密算法,RSA原理这部分我就不多说了。报文涉及到Base64的编码和解码
这是我学习之后的,参考网上的写法,写的一个工具类

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author LiuJunbao
 * @version 1.0
 * @date 2021/9/2 16:31
 */
public class RsaUtil {
    /**
     * 公钥,也可以自动是生成,这里指定
     */
    private static String publicKey;
    /**
     * 私钥,也可以自动是生成,这里指定
     */
    private static String privateKey;

    static {
        // 1、初始化密钥
        KeyPairGenerator keyPairGenerator;
        try {
            // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            // 初始化密钥对生成器
            keyPairGen.initialize(1024, new SecureRandom());
            // 生成一个密钥对,保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // 得到私钥
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            // 得到公钥
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            publicKey = Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded());
            // 得到私钥字符串
            privateKey = Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            System.out.println("生成RSA公钥私钥失败");
            e.printStackTrace();
        }
    }

    /**
     * 公钥加密
     * @param str 需要加密的数据
     * @return 加密之后的数据,加密之后经过了Base64编码
     */
    public static String publicEnCode(String str){
        String encodeStr = null;
        // Base64解码
        try {
            byte[] publicCode = Base64.getDecoder().decode(publicKey);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicCode);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
            byte[] result = cipher.doFinal(str.getBytes("UTF-8"));
            // Base64编码
            encodeStr = Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("公钥加密失败");
        }
        return encodeStr;
    }

    /**
     * 私钥加密
     * @param str 需要加密的数据
     * @return 加密之后的数据,加密之后经过了Base64编码
     */
    public static String privateEnCode(String str){
        String encodeStr = null;
        try{
            byte[] privateCode = Base64.getDecoder().decode(privateKey);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateCode);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, rsaPrivateKey);
            byte[] result = cipher.doFinal(str.getBytes("UTF-8"));
            // Base64编码
            encodeStr = Base64.getEncoder().encodeToString(result);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("公钥加密失败");
        }
        return encodeStr;
    }
    /**
     * 公钥解密
     * @param str 加密的数据
     * @return 解密之后的数据
     */
    public static String publicDeCode(String str){
        String decodeStr = null;
        try{
            //64位解码加密后的字符串
            byte[] inputByte = Base64.getDecoder().decode(str);
            byte[] publicCode = Base64.getDecoder().decode(publicKey);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicCode);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey  rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, rsaPublicKey);
            byte[] result = cipher.doFinal(inputByte);
            decodeStr = new String(result);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("公钥加密失败");
        }
        return decodeStr;
    }
    /**
     * 私钥解密
     * @param str 加密的数据
     * @return 解密之后的数据
     */
    public static String privateDeCode(String str){
        String decodeStr = null;
        try{
            //64位解码加密后的字符串
            byte[] inputByte = Base64.getDecoder().decode(str);
            byte[] privateCode = Base64.getDecoder().decode(privateKey);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateCode);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKey  rsaPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
            byte[] result = cipher.doFinal(inputByte);
            // Base64编码
            decodeStr = new String(result);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("公钥加密失败");
        }
        return decodeStr;
    }

    public static void main(String[] args) {
        String str = "hello world";
        String publicEnCode = RsaUtil.publicEnCode(str);
        System.out.println("公钥加密之后的数据为:" + publicEnCode);
        String privateDeCode = RsaUtil.privateDeCode(publicEnCode);
        System.out.println("私钥解密之后的数据为:" + privateDeCode);

        String privateEnCode = RsaUtil.privateEnCode(str);
        System.out.println("私钥加密之后的数据为:" + privateEnCode);
        String publicDeCode = RsaUtil.publicDeCode(privateEnCode);
        System.out.println("公钥解密之后的数据为:" + publicDeCode);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值