gpt4 book ai didi

java - 线程 "main"javax.crypto.BadPaddingException : Decryption error 中的异常

转载 作者:行者123 更新时间:2023-12-05 07:54:59 27 4
gpt4 key购买 nike

我在线程“main”中得到异常

javax.crypto.BadPaddingException: Decryption error in the RSA encryption/decryption.

我的 java 类是 Client、Server 并且是这样的

客户端

public class Client {

private static SecretKeySpec AES_Key;
private static String key;

public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {

Socket mySocket = null;
PrintWriter out = null;
BufferedReader in = null;

try {
mySocket = new Socket("localhost", 4443);
out = new PrintWriter(mySocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser, m1;
byte[] input;
System.out.println("Client run ");
int cnt = 0;
while (true) {
// fromServer = in.readLine();
m1 = in.readLine();
//input=in.readLine().getBytes();
if (m1 != null && cnt < 1) {
cnt++;

byte[] m = new BASE64Decoder().decodeBuffer(m1);
PrivateKey privKey = readKeyFromFile("/privateClient.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plaintext_decrypted = cipher.doFinal(m);

fromServer = new String(plaintext_decrypted, "ASCII");

AES_Key = new SecretKeySpec(fromServer.getBytes(), "AES");
System.out.println("RSA communication ends");
System.out.println("AES communication established");
}
System.out.println("type message :");

//Encrypt msg to send
Cipher AES_Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "BC");
fromUser = stdIn.readLine();
AES_Cipher.init(Cipher.ENCRYPT_MODE, AES_Key);
byte plaintext[] = fromUser.getBytes();
byte[] final_plaintext = AES_Cipher.doFinal(plaintext);
String msg = new BASE64Encoder().encode(final_plaintext);

if (fromUser != null) {
out.println(fromUser);
} else {
break;
}

fromServer = in.readLine();
if (fromServer != null) {
// Decrypt the message received
AES_Cipher.init(Cipher.DECRYPT_MODE, AES_Key);
input = new BASE64Decoder().decodeBuffer(fromServer);
byte plaintext_decrypted[] = AES_Cipher.doFinal(input);
fromServer = new String(plaintext_decrypted, "ASCII");

System.out.println("Client receive :" + fromServer);
} else {
break;
}
}

out.close();
in.close();
stdIn.close();
mySocket.close();
}

static PrivateKey readKeyFromFile(String keyFileName) throws IOException {
InputStream in
= Client.class.getResourceAsStream(keyFileName);
ObjectInputStream oin
= new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(keySpec);
return privKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}

static PublicKey readKeyFromFilePb(String keyFileName) throws IOException {
InputStream in
= Client.class.getResourceAsStream(keyFileName);
ObjectInputStream oin
= new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}

static byte[] rsaDecrypt(byte[] in) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
PrivateKey privKey = readKeyFromFile("/publicServer.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] cipherData = cipher.doFinal(in);
return cipherData;
}

static byte[] rsaEncrypt(byte[] data) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
PublicKey pubKey = readKeyFromFilePb("/privateClient.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}

private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();

int len = block.length;

for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
if (i < len - 1) {
buf.append(":");
}
}
return buf.toString();
}

/*
* Converts a byte to hex digit and writes to the supplied buffer
*/
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
}

服务器

public class Server {

private static SecretKeySpec AES_Key;
private static final String key = "1234567890ABCDEF";
public static PublicKey keycl;

public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InstantiationException, IllegalAccessException {

AES_Key = new SecretKeySpec(key.getBytes(), "AES");
//System.out.println(AES_Key);

ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4443);
} catch (IOException e) {
System.err.println("Could not listen on port: 4443.");
System.exit(1);
}

Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String inputLine, outputLine;

System.out.println("Server run ");

int cnt = 0;

byte final_plaintext[];

byte[] AES = key.getBytes();

PublicKey pubKey = readKeyFromFile("/publicClient.key");
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
final_plaintext = cipher.doFinal(AES);

String m = new BASE64Encoder().encode(final_plaintext);


System.out.println(m);
out.println(m);

while ((inputLine = in.readLine()) != null) {
cnt++;
Cipher AES_Cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "BC");
AES_Cipher.init(Cipher.DECRYPT_MODE, AES_Key);
byte[] input = new BASE64Decoder().decodeBuffer(inputLine);
//System.out.println(input);
byte plaintext_decrypted[] = AES_Cipher.doFinal(input);
inputLine = new String(plaintext_decrypted, "UTF-8");

System.out.println("Server receive : " + inputLine);
System.out.println("type message :");
outputLine = stdIn.readLine();

AES_Cipher.init(Cipher.ENCRYPT_MODE, AES_Key);
byte plaintext[] = outputLine.getBytes();
final_plaintext = AES_Cipher.doFinal(plaintext);
String msg = new BASE64Encoder().encode(final_plaintext);

out.println(msg);
}

out.close();
in.close();
clientSocket.close();
serverSocket.close();
}

public static PublicKey readKeyFromFile(String keyFileName) throws IOException {
InputStream in
= Server.class.getResourceAsStream(keyFileName);
ObjectInputStream oin
= new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}

public static byte[] rsaEncrypt(byte[] data) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
PublicKey pubKey = readKeyFromFile("/privateServer.key");
System.out.println(pubKey);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}

public static byte[] rsaDecrypt(byte[] data) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
PublicKey pubKey = readKeyFromFile("/publicClient.key");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
}

private static String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();

int len = block.length;

for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
if (i < len - 1) {
buf.append(":");
}
}
return buf.toString();
}

/*
* Converts a byte to hex digit and writes to the supplied buffer
*/
private static void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
}

生成 key

public class KeyPair  {



public KeyPair() {

}

public void GenerateKey(String name) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
java.security.KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.getPrivate();
KeyFactory fact = KeyFactory.getInstance("RSA");

RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
System.out.println(pub);

String publ="public"+name+".key";
String priva="private"+name+".key";

saveToFile(publ, pub.getModulus(),
pub.getPublicExponent());
saveToFile(priva, priv.getModulus(),
priv.getPrivateExponent());

}

public void saveToFile(String fileName,
BigInteger mod, BigInteger exp) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
} finally {
oout.close();
}
}

public PublicKey readKeyFromFile(String keyFileName) throws IOException {
InputStream in
= KeyPair.class.getResourceAsStream(keyFileName);
ObjectInputStream oin
= new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
}



public class Main {

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

KeyPair kpC = new KeyPair();
KeyPair kpS = new KeyPair();
kpS.GenerateKey("Server");
kpC.GenerateKey("Client");




}

}

最佳答案

我找到了。这是在

Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");

在客户端代码。之前是 (Cipher cipher = Cipher.getInstance("RSA");)。

关于java - 线程 "main"javax.crypto.BadPaddingException : Decryption error 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30502290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com