Java实现RSA加解密

Java实现RSA加解密

需要引入的依赖

<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.8</version>
        </dependency>

RSA密钥对生成工具类

package cn.demo.rsa;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

public class RSAKeyGenUtil {

    /**
     * 密钥大小,单位bit
     */
    private static final int KEY_SIZE = 1024;

    private static HashMap<String, String> createBase64RSAKey() throws NoSuchAlgorithmException {

        HashMap<String, String> ssMap = new HashMap<>();

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);

        //生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();

        String pub = new String(Base64.getEncoder().encode(pubKey.getEncoded()));
        String pri = new String(Base64.getEncoder().encode(priKey.getEncoded()));
        System.out.println("公钥:" + pub);
        System.out.println("私钥:" + pri);

        ssMap.put("publicKey",pub);
        ssMap.put("privateKey",pri);
        return ssMap;
    }

    /**
     * 生成的公钥和私钥文件,最好放到项目的classpath下,以便app读取
     */
    private static void  genRSAKeyFile(){
        HashMap<String, String> ssMap = new HashMap<>();
        try {
            ssMap = createBase64RSAKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (CollUtil.isNotEmpty(ssMap)){
            File pubKeyFile = FileUtil.writeBytes(ssMap.get("publicKey").getBytes(),
                    "D:/rsa2/rsa_public.key");
            System.out.println(pubKeyFile.getAbsolutePath());

            File priKeyFile = FileUtil.writeBytes(ssMap.get("privateKey").getBytes(),
                    "D:/rsa2/rsa_private.key");
            System.out.println(priKeyFile.getAbsolutePath());

        }

    }

    public static void main(String[] args) {
        genRSAKeyFile();
    }



}

RSA加解密工具类

package cn.demo.rsa;

import cn.hutool.core.io.FileUtil;

import javax.crypto.Cipher;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAjjmUtils {

    /**
     * rsa加密
     * @param yw  原文
     * @param rsaPublicKeyFilePath  rsa公钥文件路径
     * @return 密文
     * @throws Exception
     */
    public static String encrypt(String yw,String rsaPublicKeyFilePath) throws Exception {
        String utf8StringPubk = FileUtil.readUtf8String(rsaPublicKeyFilePath);
        byte[] publicKeyBytes = utf8StringPubk.getBytes();
        X509EncodedKeySpec x =
                new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBytes));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(x);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        byte[] result = cipher.doFinal(yw.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(result);
    }


    /**
     * rsa解密
     * @param mw  密文
     * @param rsaPrivateKeyFilePath rsa私钥文件路径
     * @return 原文
     * @throws Exception
     */
    public static String decrypt(String mw,String rsaPrivateKeyFilePath) throws Exception{
        String utf8StringPrik = FileUtil.readUtf8String(rsaPrivateKeyFilePath);
        byte[] privateKeyBytes = utf8StringPrik.getBytes();
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec =
                new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBytes));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        byte[] result = cipher.doFinal(Base64.getDecoder().decode(mw));
        return new String(result);

    }


    public static void main(String[] args) throws Exception {
//        File pubKeyFile = FileUtil.file("D:/rsa2/rsa_public.key");
        File pubKeyFile = FileUtil.file("classpath:rsa_public.key");
        String encryptStr = encrypt("20230609", pubKeyFile.getPath());
        System.err.println(encryptStr); //密文每次都不一样

//        File filePrk = FileUtil.file("D:/rsa2/rsa_private.key");
        File filePrk = FileUtil.file("classpath:rsa_private.key");
        String decryptStr = decrypt(encryptStr, filePrk.getPath());
        System.err.println(decryptStr); //解出的明文都是 20230609
    }



}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ThinkPet

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

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

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

打赏作者

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

抵扣说明:

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

余额充值