Java实现RSA加解密

Java实现RSA加解密

需要引入的依赖


            cn.hutool
            hutool-all
            5.7.8
        

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
    }



}


你可能感兴趣的:(JavaSE笔记,java,RSA,密钥对,加解密,非对称加密)