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

seedjeffwan 2012-11-27 07:20:25
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"));
}
}
...全文
999 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
seedjeffwan 2012-11-28
  • 打赏
  • 举报
回复
为啥一个回复也没有啊~啊~啊~
【课程介绍】     课程目标:             - 有状态登录和无状态登录的区别             - 常见的非对称加密算法和非对称的加密方式             - 老版本只使用jwt进行加密的弊端             - 授权中心的授权流程             - 如何整合网关组件实现jwt安全验证             - 理解什么是公钥什么是私钥      - 深刻理解授权流程什么是有状态? 有状态服务,即服务端需要记录每次会话的客户端信息,从而识别客户端身份,根据用户身份进行请求的处理,典型的设计如tomcat中的session。例如登录:用户登录后,我们把登录者的信息保存在服务端session中,并且给用户一个cookie值,记录对应的session。然后下次请求,用户携带cookie值来,我们就能识别到对应session,从而找到用户的信息。缺点是什么?- 服务端保存大量数据,增加服务端压力- 服务端保存用户状态,无法进行水平扩展- 客户端请求依赖服务端,多次请求必须访问同一台服务器。什么是无状态? 微服务集群中的每个服务,对外提供的都是Rest风格的接口。而Rest风格的一个最重要的规范就是:服务的无状态性,即:- 服务端不保存任何客户端请求者信息- 客户端的每次请求必须具备自描述信息,通过这些信息识别客户端身份带来的好处是什么呢?- 客户端请求不依赖服务端的信息,任何多次请求不需要必须访问到同一台服务- 服务端的集群和状态对客户端透明- 服务端可以任意的迁移和伸缩- 减小服务端存储压力

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧