公私钥加密解密

本文介绍了一个使用Java实现的RSA加密和解密过程。通过生成公钥和私钥对,利用公钥加密“测试数据”并保存加密后的数据及私钥。随后使用私钥进行解密操作,并成功还原原始信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package com.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import javax.crypto.Cipher;

public class CipherRSA {

public static void main(String[] args) throws Exception {
new CipherRSA().publicEncrypt();
new CipherRSA().privateDecrypt();
}

public void publicEncrypt() throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keypairGenerator.generateKeyPair();
Key publicKey = keyPair.getPublic();
Key privateKey = keyPair.getPrivate();
saveKey(privateKey, "private_key");
cipher.init(Cipher.ENCRYPT_MODE,publicKey);
byte[] data = cipher.doFinal("测试数据".getBytes("UTF-8"));
saveData(data,"public_data");
}

public void privateDecrypt() throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
Key privateKey = readKey("private_key");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] data = readData("public_data");
byte[] rs = cipher.doFinal(data);
System.out.println(new String(rs,"UTF-8"));
}

public void saveData(byte[] data, String fileName) throws Exception{
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
fos.close();
}

public void saveKey(Key key, String fileName) throws Exception{
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(key);
oos.close();
fos.close();
}

public Key readKey(String fileName) throws Exception{
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Key privateKey = (Key)ois.readObject();
return privateKey;
}

public byte[] readData(String fileName) throws Exception{
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
byte[] data = (byte[])ois.readObject();
return data;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值