我正在研究java客户端服务器aes加密哪个服务器加密和客户端解密。但是我有填充错误可能为byte []和string..i无法解决它。任何人都可以告诉我要改变什么来解决加密和解密问题?
SERVER
public void run(){
try {
String key1 = "1234567812345678";
byte[] key2 = key1.getBytes();
SecretKeySpec secret = new SecretKeySpec(key2, "AES");
String msg = "Singapore Malaysia Japan India";
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] encrypted = cipher.doFinal(msg.getBytes());
in = new DataInputStream(incoming.getInputStream());
out = new DataOutputStream(incoming.getOutputStream());
boolean done = false;
String str="";
out.writeUTF("Connected!\n");
out.flush();
while (!done){
out.writeUTF(">");
out.flush();
str = in.readUTF();
System.out.println(in+":"+str);
if (str == null)
done = true;
else{
System.out.println("Sending Ciphertext : " + new String(encrypted));
out.writeUTF(new String(encrypted));
out.flush();
客户端
String str = "";
String str2 = "";
DataOutputStream out;
DataInputStream in;
try {
Socket t = new Socket("127.0.0.1", 9003);
in = new DataInputStream(t.getInputStream());
out = new DataOutputStream(t.getOutputStream());
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
boolean more = true;
System.out.println(in.readUTF());
while (more) {
str = in.readUTF();
System.out.print(str);
str2 = br.readLine();
out.writeUTF(str2);
out.flush();
str = in.readUTF();
System.out.println("Encrypted Info: " + str);
try {
String key1 = "1234567812345678";
byte[] key2 = key1.getBytes();
SecretKeySpec secret = new SecretKeySpec(key2, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret);
byte[] decrypted = cipher.doFinal(str.getBytes());
System.out.println("Decrypted Info: " + new String(decrypted));
}
答案 0 :(得分:2)
所有字符串都可以转换为字节,但不一定是相反的情况;字节并不总是有效的字符串。
因此,您需要做的是以二进制形式传输密文,或者您需要使用以下方法将字节专门编码为字符。 base 64编码。