RSA 公钥解密时候报错 BadPaddingException异常,麻烦大家看看

seedjeffwan seedjeffwan 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
client端和server端进行通信,分别是Alice和Bob,Client端加密,用流传给Server端,server解密,整个过程模拟RSA加密解密,考虑保密性和完整性。
Alice用Bob公钥加密,bob这边用自己私钥解密,没问题,但是Alice用自己私钥加密,Bob用Alice公钥解密时候,就报错,BadPaddingException异常
最开始我是直接用cipher.dofinal的,出问题,以为是RSA 分组加密问题,后来找了分组加密的代码,还是不行,我感觉可能是流传递的问题,但是怎么也弄不出来,麻烦大家看看。

Alice.java

package RSA2;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class Alice {
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
public static String ciphermode = "RSA/ECB/PSCS7Padding";

private static byte[] confidentiality(String message, Key publicKeyBob) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, Exception {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.ENCRYPT_MODE, publicKeyBob);

byte[] data = message.getBytes();
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
private static byte[] intergrity(String message, Key privateKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.ENCRYPT_MODE, privateKeyAlice);

byte[] data = message.getBytes();
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;


}
private static byte[] conAndInter(String message, Key publicKeyBob, Key privateKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.ENCRYPT_MODE, privateKeyAlice);
byte[] result=cipher.doFinal(message.getBytes("UTF-8"));

cipher.init(Cipher.ENCRYPT_MODE, publicKeyBob);
return cipher.doFinal(result);
}


public static void main(String[] args) throws Exception {
int port = 7999;
String host = "127.0.0.1";
Socket s = new Socket(host,port);

//Key Generator
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keypair = keyPairGenerator.generateKeyPair();
Key publicKeyAlice = keypair.getPublic();
Key privateKeyAlice = keypair.getPrivate();


FileOutputStream fos = new FileOutputStream("E:\\workspace2\\publicKeyAlice.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(publicKeyAlice);
oos.close();
fos.close();


FileInputStream fis = new FileInputStream("E:\\workspace2\\publicKeyBob.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Key publicKeyBob =(Key)ois.readObject();
ois.close();
fis.close();




String message ="i wanner finish lab!";

byte[] result = null;
switch(2)
{
case 1:
result = confidentiality(message,publicKeyBob);
break;
case 2:
result = intergrity(message,privateKeyAlice);
break;
case 3:
result = conAndInter(message,publicKeyBob,privateKeyAlice);
}


DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeInt(result.length);
dos.write(result, 0, result.length);
System.out.println(new String(result));
// bw.write(bytesToString(result));
System.out.println("finished");
dos.close();


}



}


Bob.class (帖子有字数限制,bob的包不打出来了)


package RSA2;
public class Bob {
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
public static String ciphermode = "RSA/ECB/PSCS7Padding";

private static byte[] confidentiality(byte[] encryptedData, Key privateKeyBob) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, Exception {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.DECRYPT_MODE, privateKeyBob);

int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;

}
private static byte[] intergrity(byte[] encryptedData, Key publicKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {

Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.DECRYPT_MODE, publicKeyAlice);

int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;

}
private static byte[] conAndInter(byte[] encryptedData, Key publicKeyAlice, Key privateKeyAlice) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance(ciphermode);
cipher.init(Cipher.DECRYPT_MODE, publicKeyAlice);

//cipher.update(input, output)
byte[] result = cipher.doFinal();
return result;
}
private static byte[] stringToByte(String message){
String[] strArr = message.split(" ");
int len = strArr.length;
byte[] clone = new byte[len];
for (int i = 0; i < len; i++) {
clone[i] = Byte.parseByte(strArr[i]);
}
return clone;
}

public static void main(String[] args) throws Exception {
int port = 7999;
ServerSocket server = new ServerSocket(port);

//Key Generation
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keypair = keyPairGenerator.generateKeyPair();
Key publicKeyBob = keypair.getPublic();
Key privateKeyBob = keypair.getPrivate();

FileOutputStream fos = new FileOutputStream("E:\\workspace2\\publicKeyBob.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(publicKeyBob);
oos.close();
fos.close();
//System.out.println("have writen bob's publickey ");

System.out.println("waiting for connection ");
Socket s = server.accept();
System.out.println("conntect successfully ");

FileInputStream fis = new FileInputStream("E:\\workspace2\\publicKeyAlice.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Key publicKeyAlice =(PublicKey)ois.readObject();
ois.close();
fis.close();



//读内容
DataInputStream dis = new DataInputStream(s.getInputStream());
int len = dis.readInt();
byte[] encryptedData = new byte[len];
dis.read(encryptedData, 0, len);


//Decryption
byte[] result= null;
switch(2)
{

case 1:
result = confidentiality(encryptedData,privateKeyBob);
break;
case 2:
result = intergrity(encryptedData,publicKeyAlice);
break;
// case 3:
// result = conAndInter(message,privateKeyBob,publicKeyAlice,cipher);
}

System.out.println("Decrypted message: "+new String(result,"UTF-8"));
}
}
...全文

相关推荐

Java进行RSA加解密的例子

加密是保证数据安全的手段之一。加密是将纯文本数据转换为难以理解的密文;解密是将密文转换回纯文本。   数据的加解密属于密码学的范畴。通常,加密和解密都需要使用一些秘密信息,这些秘密信息叫做密钥,将纯文本转为密文或者转回的时候都要用到这些密钥。   对称加密指的是发送者和接收者共用同一个密钥的加解密方法。   非对称加密(又称公钥加密)指的是需要一个私有密钥一个公开密钥,两个不同的密钥的加解密体系。尽管不同,这个密钥对的这两个部分在算法上是有关联的。一个密钥将纯文本加密,另一个将密文解密。没有一个密钥能够把加密和加密的功能全部自己完成。公钥,或者用于加密数据的密钥,可以被自由分发。   

weixin_38722874

Java RSA解密BadPaddingException根因与填充协议对齐指南

RSA填充机制是保障非对称加密安全性的基础工程契约,其核心作用在于防止小明文攻击和实现语义安全性。PKCS#1 v1.5与OAEP作为两种主流填充方案,分别对应不同数学结构与校验逻辑,一旦加解密端填充算法不一致,Java原生javax.crypto就会抛出BadPaddingException——该异常本质是填充结构解析失败,而非密钥或算法错误。在跨平台场景中,Web Crypto API默认OAEP、Android/iOS系统级API倾向OAEP,而Java Cipher.getInstance("RSA

刘子栋

Java版MD5和RSA加解密算法完整实现

Java版MD5和RSA加解密算法完整实现,欢迎分享!

thankkai

基于Java语言实现AES对称加密与RSA非对称加密算法深度整合与安全交互机制的综合性示例工程_涵盖AES密钥生成数据块加密解密填充模式处理RSA密钥对创建公钥加密私钥解密.zip

基于Java语言实现AES对称加密与RSA非对称加密算法深度整合与安全交互机制的综合性示例工程_涵盖AES密钥生成数据块加密解密填充模式处理RSA密钥对创建公钥加密私钥解密.zip

nihao2025123

Java built-in methods for RSA encryption and decryption

打开链接下载源码: https://pan.quark.cn/s/a4b39357ea24 gorsa gorsa 支持rsa公钥加密私钥解密;支持rsa公钥解密私钥加密。 gorsa 使用方法 使用方法:

chaoyunsmumudn
评论 1
收藏 已收藏
分享
返回顶部
seedjeffwan
Java SE 62,621 成员 307,251 内容