此代码在服务器端提供无效的AES密钥长度错误。我该如何纠正?之后,当从客户端服务器发送msg时出现错误,就会创建服务器。
服务器代码:
import java.io.*;
import java.net.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6808);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
//SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
SecretKeySpec skeySpec = new SecretKeySpec(Base64.decodeBase64(raw), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(skeySpec.getEncoded(),"AES"));
byte[] original = cipher.doFinal(Base64.decodeBase64(clientSentence));
original.toString();
System.out.println("Sent: " + original);
capitalizedSentence = (new String(original)).toUpperCase() + '\n';
System.out.println("Sent: " + capitalizedSentence);
outToClient.writeBytes(capitalizedSentence);
}
}
}
客户代码:
import java.io.*;
import java.net.*;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6808);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sentence.getBytes());
System.out.println("encrypted string:" + (new String(encrypted)));
outToServer.writeBytes(new String(encrypted) + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
任何帮助表示感谢。
答案 0 :(得分:1)
取消注释skeySpec并直接使用raw
密钥,就像在客户端中一样。
//SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
SecretKeySpec skeySpec = new SecretKeySpec(Base64.decodeBase64(raw), "AES");