Java创建RSA非对称密钥,读取私钥,使用私钥

该代码示例展示了如何在Java中生成RSA密钥对,将密钥保存为二进制和PEM格式,并进行加密解密操作。同时,它还包含了从DER编码的密钥文件中读取并转换为PEM格式的过程。
摘要由CSDN通过智能技术生成

创建私钥(二进制,base64)

package com.hongdou.weChatPay.util;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectOutputStream;
import java.security.*;
import java.util.Base64;

public class KeyPairGeneratorExample {
    public static void main(String[] args) throws Exception {
        // Generate RSA key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // key size
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        // 保存私钥到本地文件(二进制私钥)
        FileOutputStream privateKeyFileOut = new FileOutputStream("E:\\video\\privateKey.dat");
        ObjectOutputStream privateKeyObjOut = new ObjectOutputStream(privateKeyFileOut);
        privateKeyObjOut.writeObject(privateKey);
        privateKeyObjOut.close();

        // 保存公钥到本地文件(二进制公钥)
        FileOutputStream publicKeyFileOut = new FileOutputStream("E:\\video\\publicKey.dat");
        ObjectOutputStream publicKeyObjOut = new ObjectOutputStream(publicKeyFileOut);
        publicKeyObjOut.writeObject(publicKey);
        publicKeyObjOut.close();

        // Convert private key to PEM format and save to file
        String privateKeyPEM = convertToPEM(privateKey);
        FileWriter privateFileWriter = new FileWriter("E:\\video\\private_key.pem");
        privateFileWriter.write(privateKeyPEM);
        privateFileWriter.close();

        // Convert public key to PEM format and save to file
        String publicKeyPEM = convertToPEM(publicKey);
        FileWriter publicFileWriter = new FileWriter("E:\\video\\public_key.pem");
        publicFileWriter.write(publicKeyPEM);
        publicFileWriter.close();
    }

    private static String convertToPEM(Key key) {
        //获取base64编码,每行64字符
        String encoded = Base64.getMimeEncoder(64, System.lineSeparator().getBytes()).encodeToString(key.getEncoded());
        if (key instanceof PrivateKey) {
            return "-----BEGIN PRIVATE KEY-----" + System.lineSeparator()
                    + encoded + System.lineSeparator()
                    + "-----END PRIVATE KEY-----";
        } else {
            return "-----BEGIN PUBLIC KEY-----" + System.lineSeparator()
                    + encoded + System.lineSeparator()
                    + "-----END PUBLIC KEY-----";
        }
    }
}

使用二进制密钥

    // 读取私钥
            FileInputStream privateKeyFileIn = new FileInputStream("E:\video\\privateKey.dat");
            ObjectInputStream privateKeyObjIn = new ObjectInputStream(privateKeyFileIn);
            PrivateKey privateKey = (PrivateKey) privateKeyObjIn.readObject();
            privateKeyObjIn.close();

            // 读取公钥
            FileInputStream publicKeyFileIn = new FileInputStream("E:\video\\publicKey.dat");
            ObjectInputStream publicKeyObjIn = new ObjectInputStream(publicKeyFileIn);
            PublicKey publicKey = (PublicKey) publicKeyObjIn.readObject();
            publicKeyObjIn.close();
            
            // 加密信息
            String message = "Hello World!";
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedMessage = cipher.doFinal(message.getBytes());
            System.out.println("Encrypted Message: " + new String(encryptedMessage));
            // 解密信息
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedMessage = cipher.doFinal(encryptedMessage);
            System.out.println("Decrypted Message: " + new String(decryptedMessage));

对二进制密钥做base64编码(私钥)

 // 读取DER编码的密钥文件
        File derFile = new File("C:\\tmp\\qq\\privateKey.dat");
        byte[] derBytes;
        try {
            FileInputStream fis = new FileInputStream(derFile);
            derBytes = new byte[(int) derFile.length()];
            fis.read(derBytes);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        // 转换为PEM格式
        byte[] pemBytes = Base64.encodeBase64(derBytes);
        String pemString = new String(pemBytes);

        // 输出到磁盘上的文件
        File pemFile = new File("C:\\tmp\\qq\\privateKey.pem");
        try {
            FileWriter fw = new FileWriter(pemFile);
            fw.write("-----BEGIN PRIVATE KEY-----\n");
            fw.write(pemString);
            fw.write("\n-----END PRIVATE KEY-----\n");
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

对二进制密钥做base64编码(公钥)

 // 读取DER编码的密钥文件
        File derFile = new File("C:\\tmp\\qq\\publicKey.dat");
        byte[] derBytes;
        try {
            FileInputStream fis = new FileInputStream(derFile);
            derBytes = new byte[(int) derFile.length()];
            fis.read(derBytes);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        // 转换为PEM格式
        byte[] pemBytes = Base64.encodeBase64(derBytes);
        String pemString = new String(pemBytes);
        // 输出到磁盘上的文件
        File pemFile = new File("C:\\tmp\\qq\\publicKey.pem");
        try {
            FileWriter fw = new FileWriter(pemFile);
            fw.write("-----BEGIN PUBLIC KEY-----\n");
            fw.write(pemString);
            fw.write("\n-----BEGIN PUBLIC KEY-----\n");
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值