Java RSA 加密解密中 密钥保存并读取,数据加密解密并保存读取 问题

2025-03-21 23:38:25
推荐回答(3个)
回答1:

帮你完善了下代码。

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Map;

public class Test {
    static String publicKey;
    static String privateKey;

    public Test() throws Exception {
        // TODO Auto-generated constructor stub
        Map keyMap = RSAUtils.genKeyPair();
        publicKey = RSAUtils.getPublicKey(keyMap);
        privateKey = RSAUtils.getPrivateKey(keyMap);

        // 保存密钥,名字分别为publicKey。txt 和privateKey。txt;
        PrintWriter pw1 = new PrintWriter(new FileOutputStream(
                "D:/publicKey.txt"));
        PrintWriter pw2 = new PrintWriter(new FileOutputStream(
                "D:/privateKey.txt"));
        pw1.print(publicKey);
        pw2.print(privateKey);
        pw1.close();
        pw2.close();

        // 从保存的目录读取刚才的保存的公钥,
        String pubkey = readFile("D:/publicKey.txt");// 读取的公钥内容;
        String data = readFile("D:/1.txt"); // 需要公钥加密的文件的内容(如D:/1.txt)
        byte[] encByPubKeyData = RSAUtils.encryptByPublicKey(data.getBytes(),
                pubkey);
        //将加密数据base64后写入文件
        writeFile("D:/Encfile.txt", Base64Utils.encode(encByPubKeyData).getBytes("UTF-8"));
        // 加密后的文件保存在

        String prikey = readFile("D:/privateKey.txt");// 从保存的目录读取刚才的保存的私钥,
        String Encdata = readFile("D:/Encfile.txt");// 刚才加密的文件的内容;
        byte[] encData = Base64Utils.decode(Encdata);
        byte[] decByPriKeyData = RSAUtils.decryptByPrivateKey(encData, prikey);
        // 解密后后的文件保存在D:/Decfile.txt
        writeFile("D:/Decfile.txt", decByPriKeyData);
    }

    private static String readFile(String filePath) throws Exception {
        File inFile = new File(filePath);
        long fileLen = inFile.length();
        Reader reader = new FileReader(inFile);

        char[] content = new char[(int) fileLen];
        reader.read(content);
        System.out.println("读取到的内容为:" + new String(content));
        return new String(content);
    }

    private static void writeFile(String filePath, byte[] content)
            throws Exception {
        System.out.println("待写入文件的内容为:" + new String(content));
        File outFile = new File(filePath);
        OutputStream out = new FileOutputStream(outFile);
        out.write(content);
        if (out != null) out.close();
    }

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        new Test();
    }

}

测试结果:

读取到的内容为:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVr9D9hYPD4kS5k86dRm+utyt5XGOSTPwT0YeoBnQmgeISkNsbtUFkY6txyodVl26IM1H5iwJ1jMQ63+lXfZxzNpeA+rHaxmeQ2qI+5ES9AF7G6KIwjzakKsA08Ly+1y3dp0BnoyHF7/Pj3AS28fDmE5piea7w36vp4E3Ts+F9vwIDAQAB
读取到的内容为:锘县ahaha

回答2:

【实例下载】本文介绍RSA2加密与解密,RSA2是RSA的加强版本,在密钥长度上采用2048, RSA2比RSA更安全,更可靠, 本人的另一篇文章RSA已经发表,有想了解的可以点开下面的RSA文章

回答3:

getBytes的时候用getBytes("UTF8")试试看呢?