我正在编写使用aes的服务器/客户机系统。以下方法(服务器端)工作正常:
public static byte[] encode(byte type, byte subType, String string, Cipher cipher)
throws NullPointerException, IOException {
Objects.requireNonNull(string);
Objects.requireNonNull(cipher);
byte[] data = null;
try {
data = string.getBytes(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e1) {};
ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();
bytesOutput.write(type);
bytesOutput.write(subType);
bytesOutput.write(data);
byte[] plainBytes = bytesOutput.toByteArray();
byte[] bytes = null;
try {
bytes = cipher.doFinal(plainBytes);
} catch (Exception e) {
e.printStackTrace();
}
byte[] base64Bytes = Base64.getEncoder().encode(bytes);
return base64Bytes;
}
但是当我用下面的代码替换它时,客户端出现了illegalblocksizeexception。
public static byte[] encode(byte type, byte subType, String string, Cipher cipher)
throws NullPointerException, EncodingException {
Objects.requireNonNull(string);
Objects.requireNonNull(cipher);
byte[] data = null;
try {
data = string.getBytes(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e1) {};
CipherOutputStream cipherOutput = null;
try {
ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();
OutputStream base64Output = Base64.getEncoder().wrap(bytesOutput);
cipherOutput = new CipherOutputStream(base64Output, cipher);
cipherOutput.write(type);
cipherOutput.write(subType);
cipherOutput.write(data);
cipherOutput.flush();
byte[] bytes = bytesOutput.toByteArray();
return bytes;
} catch (IllegalStateException | IOException e) {
throw new EncodingException(e);
} finally {
if (cipherOutput != null)
try {
cipherOutput.close();
} catch (IOException e) {};
}
}
}
第二种方法有什么问题?两种方法使用相同的密码。除了encode方法外,服务器上没有任何更改。
暂无答案!
目前还没有任何答案,快来回答吧!