RSA 公私钥加解密Java实现

1.简单快速集成,饮用hutool工具包实现

1)引入hutool包

        
            cn.hutool
            hutool-all
            5.8.8
        

2) 制作好自己的rsa公私钥文件,通过openssl实现即可,直接放到resources下面 

RSA 公私钥加解密Java实现_第1张图片

3)读取rsa文件,进行加解密实现,公钥加密,私钥解密,注意点都在里面注释了。

package com.shebao.controller.wechat;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class HutoolRSATest {

    public static void main(String[] args) throws IOException {
        String en = testEncrypt();
        testDecrypt(en);
    }

    /**
     * 私钥解密
     * @param content 加密了的内容
     * @throws IOException
     */
    public static void testDecrypt(String content) throws IOException {
        Resource resource = new ClassPathResource("rsa_private_key.pem");
        System.out.println(resource.getFile().getPath());
        BufferedReader br = new BufferedReader(new FileReader(resource.getFile().getPath()));
        /**
         * 这个巨重要,会筛选掉密钥内容中的首行标识字段
         */
        String s = br.readLine();
        String str = "";
        s = br.readLine();
        while (s.charAt(0) != '-') {
            str += s + "\r";
            s = br.readLine();
        }
        RSA rsa = new RSA(str,null);
        String s1 = rsa.decryptStr(content, KeyType.PrivateKey);
        System.out.println(s1);
    }

    /**
     * 公钥加密
     * @return
     * @throws IOException
     */
    public static String testEncrypt() throws IOException {
        String content = "这是糊涂工具包hutool";
        Resource resource = new ClassPathResource("rsa_public_key.pem");
        System.out.println(resource.getFile().getPath());
        BufferedReader br = new BufferedReader(new FileReader(resource.getFile().getPath()));
        String s = br.readLine();
        String str = "";
        s = br.readLine();
        while (s.charAt(0) != '-') {
            str += s + "\r";
            s = br.readLine();
        }

        RSA rsa = new RSA(null,str);
        String result = rsa.encryptBase64(content, KeyType.PublicKey);
        System.out.println(result);
        return result;
    }
}

2.不借助工具,直接引用java security包实现功能

1)公私钥依然放在resources下

2)公钥加密,私钥解密

3)java.security.Security.addProvider( new org.bouncycastle.jce.provider.BouncyCastleProvider() );这句话很重要,不过别乱用,容易导致内存泄漏:可以参看如下文章

每次New一个BouncyCastleProvider导致的内存泄漏_shenhaiwen的博客-CSDN博客

我的实例改良了这里

4)要注意base64的解码和编码

package com.shebao.controller.wechat;


import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class TestRSA {

    private static String content = "你好呀RSA";


    public static void main(String[] args) throws Exception {
        PublicKey publicKey = getPublicKey();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content.getBytes());
        byte[] bytes1 = Base64.encodeBase64(bytes);
        String result = new String(bytes1,"utf-8");
        System.out.println(result);
        test(result);

    }

    public static void test(String en) throws Exception {
        PrivateKey privateKey = getPrivate();
        KeyFactory keyFactory1 = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance(keyFactory1.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes2 = cipher.doFinal(Base64.decodeBase64(en));
        System.out.println(new String(bytes2, StandardCharsets.UTF_8));
    }

    public static PrivateKey getPrivate() throws Exception {
        Resource resource = new ClassPathResource("rsa_private_key.pem");
        System.out.println(resource.getFile().getPath());
        BufferedReader br = new BufferedReader(new FileReader(resource.getFile().getPath()));
        /**
         * 这个巨重要,会筛选掉密钥内容中的首行标识字段
         */
        String s = br.readLine();
        /**
         * 这里是读取的私钥文件
         */
        String str = "";
        s = br.readLine();
        while (s.charAt(0) != '-') {
            str += s + "\r";
            s = br.readLine();
        }

        Base64 base64 = new Base64();
        byte[] b = base64.decode(str);
        /**
         * 这个也是巨重要的,不信可以去了试试,也有另一种方式去解决这个问题,没试
         */
        BouncyCastleProvider instance = getInstance();
        if (Security.getProvider(instance.getName()) == null) {
            java.security.Security.addProvider(
                    instance
            ); 
        }

        // 生成私匙
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(b);
        PrivateKey privateKey = kf.generatePrivate(keySpec);
        return privateKey;
    }

    public static PublicKey getPublicKey() throws Exception {
        Resource resource = new ClassPathResource("rsa_public_key.pem");
        System.out.println(resource.getFile().getPath());
        BufferedReader br = new BufferedReader(new FileReader(resource.getFile().getPath()));
        String s = br.readLine();
        /**
         * 这里是读取的公钥文件
         */
        String public_key = "";
        s = br.readLine();
        while (s.charAt(0) != '-') {
            public_key += s + "\r";
            s = br.readLine();
        }

        Base64 base64 = new Base64();
        byte[] decode = base64.decode(public_key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decode);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    private static org.bouncycastle.jce.provider.BouncyCastleProvider bouncyCastleProvider = null;

    public static synchronized org.bouncycastle.jce.provider.BouncyCastleProvider getInstance() {
        if (bouncyCastleProvider == null) {
            bouncyCastleProvider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
        }
        return bouncyCastleProvider;
    }
}

你可能感兴趣的:(java,java)