Java 使用openssl生成的RSA公私钥证书加密文本内容

1.openssl 生成RSA公私钥证书

使用Linux和Windows生成都可以,我使用Linux生成的

  1. 生成私钥
openssl genrsa -out rsa_private_key.pem 1024
  1. Java需要将私钥转换成PKCS8 格式
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_private_key_pkcs8.pem
  1. 生成公钥
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

我们需要的文件是下列两个:
在这里插入图片描述
为了方便操作,我们将rsa_private_key_pkcs8.pem更名为rsa_private_key.pem

我们需要的就是文件中私钥和公钥
在这里插入图片描述
在这里插入图片描述

2.Java从输入流中获取公钥和私钥
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * RSA公私钥文件处理类
 */
public class CertificateUtils {

    /**
     * 从文件中输入流中加载公钥
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String loadPublicKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString().replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
        } catch (IOException e) {
            throw new Exception("公钥数据流读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥输入流为空");
        }
    }


    /**
     * 从文件中加载私钥
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String loadPrivateKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString().replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "");
        } catch (IOException e) {
            throw new Exception("私钥数据读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥输入流为空");
        }
    }


    public static void main(String[] args) throws Exception {
        System.out.println(loadPublicKeyByFile("D:/netplan/rsa_public_key.pem"));
        System.out.println(loadPrivateKeyByFile("D:/netplan/rsa_private_key.pem"));
    }
}
3.Java公钥加密,私钥解密字符串
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAUtils {

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RAS加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception {
        //Base64解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //Base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        PrivateKey priKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }

    public static void main(String[] args) throws Exception {
        String content = "测试加密的内容";
        // 获取公钥
        String publicKey = CertificateUtils.loadPublicKeyByFile("D:/netplan/rsa_public_key.pem");
        // 加密随机字符串
        String rsaContent = encrypt(content, publicKey);
        System.out.println("RSA加密的内容为:" + rsaContent);
        // 获取私钥
        String privateKey = CertificateUtils.loadPrivateKeyByFile("D:/netplan/rsa_private_key.pem");
        // 获取解密后的内容
        String decryptContent = decrypt(rsaContent, privateKey);
        System.out.println("RSA解密后的内容是:" + decryptContent);
    }
}

在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值