【问题标题】:"Illegal base64 character 3" with sent integer across TCP connection (AES Encrypted String)“非法 base64 字符 3”,通过 TCP 连接发送整数(AES 加密字符串)
【发布时间】: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


    【解决方案1】:

    由于大量代码丢失,很难给出更好的答案。

    我刚刚使用发布的代码并填补了缺失的空白,并且它起作用了。 (密钥算法:PBKDF2WithHmacSHA256PipedReaderPipedWriterReaderWriter

    最好发布一个完整的示例...无论如何尝试隔离问题,例如,首先尝试加密某些内容并直接解密结果以检查它是否正常工作。接下来打印出正在发送的内容和正在接收的内容(我的猜测是发送的数据与接收的数据不同)。

    显然不是直接的答案,但它应该显示一种可能的方法来找到给定信息的问题。

    【讨论】:

      猜你喜欢
      • 2020-02-17
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 2013-09-19
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多