【发布时间】:2021-09-10 02:54:09
【问题描述】:
我通过 TCP 发送了以下整数:3964956
发件人代码:
writer.write(Aes.encrypt(new String(file.length() + ""), node.getEncryptionKey()) + "\n");
writer.flush();
接收者代码:
String size;
if ((size = reader.readLine()) != null) {
if ((size = Aes.decrypt(size, node.getEncryptionKey())) == null) throw new Exception("decrypt err"); // <---
// ERROR IS ABOVE LINE
final long byteSize = Long.parseLong(size);
byte[] bytes = new byte[5 * 1024];
例外:java.lang.IllegalArgumentException: Illegal base64 character 3
当接收方尝试解密数据包时抛出异常,实际加密的代码如下。
加密类(Aes.java):
/***
* Encrypt a String using AES.
*
* @param strToEncrypt The target String to encrypt
* @param secret The secret key you wish to encrypt
* the String with, this secret key
* will be used to decrypt the String
* @return The encrypted String
*/
public static String encrypt(String strToEncrypt, String secret) throws Exception {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
/***
* Decrypt the AES Encrypted String.
*
* @param strToDecrypt The target String to decrypt
* @param secret The secret key that was used to encrypt this String
* @return The decrypted String
*/
public static String decrypt(String strToDecrypt, String secret) throws Exception {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
编辑:下面有更多代码;在上面指定的特定整数发送之前有一个完整的身份验证过程,所有数据都使用相同的 AES 加密,但是数据不会像当前那样抛出任何错误。
套接字对象
try(InputStream is = socket.getInputStream(); BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(is))){
...
}
接收整数的函数:
processStreamsForDownload(cdn_node, reader, response.getOutputStream(), is);
如果还有什么可以补充的,请告诉我。
【问题讨论】:
标签: java encryption tcp base64 illegalargumentexception