AEADBadTagException 标记不匹配套接字数据

AEADBadTagException Tag mismatch socket data

我有一个服务器,让套接字连接到它以通过输入流发送数据,此数据在一个名为 Cryptographer 的 class 中使用 AES/GCM/NoPadding 加密。服务器具有为连接的客户端保留功能的线程,并且每个线程都在 ConnectionThread class 中表示,此 class 包含对正在初始化的 cryptographer class 的引用服务器 class.

问题:

当我发送第一个命令时,它工作正常,完全没有问题。但是不知何故,当我发送第二个命令时,如果给出以下堆栈跟踪:

javax.crypto.AEADBadTagException: Tag mismatch!
    at java.base/com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:595)
    at java.base/com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1116)
    at java.base/com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1053)
    at java.base/com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
    at java.base/com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
    at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2208)
    at com.company.security.Cryptographer.decrypt(Cryptographer.java:53)
    at com.company.client.Reader.run(Reader.java:45)
    at java.base/java.lang.Thread.run(Thread.java:835)
Exception in thread "Thread-3" java.lang.NullPointerException
    at java.base/java.lang.String.<init>(String.java:623)
    at com.company.client.Reader.run(Reader.java:47)
    at java.base/java.lang.Thread.run(Thread.java:835)

这些是堆栈跟踪

中提到的classes

密码学家

package com.company.security;

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Cryptographer {
    private Key secretKey;
    private GCMParameterSpec gcmParameterSpec;

    public Cryptographer() {
        byte[] secret = new byte[16]; // 128 bit is 16 bytes, and AES accepts 16 bytes, and a few others.
        byte[] secretBytes = "secret".getBytes();
        byte[] IV = new byte[12];
        gcmParameterSpec = new GCMParameterSpec(16 * 8, IV);
        System.arraycopy(secretBytes, 0, secret, 0, secretBytes.length);
        secretKey = new SecretKeySpec(secret, "AES");
    }

    /**
     * Encrypt data.
     * @param data to encrypt
     * @return encrypted data
     */
    public byte[] encrypt(byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
            byte[] encrypted = cipher.doFinal(data);
            return encrypted;
        } catch (InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | NoSuchPaddingException
                | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Decrypt data.
     * @param data to decrypt
     * @return decrypted data
     */
    public byte[] decrypt(byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
            return cipher.doFinal(data);
        } catch (InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | NoSuchPaddingException
                | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Reader

package com.company.client;

import com.company.FileLoader;
import com.company.client.helpers.ClientFileHelper;
import com.company.client.workers.MessageSender;
import com.company.security.Cryptographer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

public class Reader implements Runnable {
    private InputStream inputStream;
    private ClientFileHelper fileHelper;
    private Cryptographer cryptographer;
    private FileLoader fileLoader;
    private BufferedReader bufferedReader;
    private MessageSender messageSender;
    private boolean isActive = true;
    private boolean isReceivingFile = false;


    public Reader(BufferedReader bufferedReader, MessageSender messageSender, InputStream inputStream) {
        this.bufferedReader = bufferedReader;
        this.messageSender = messageSender;
        this.inputStream = inputStream;
        cryptographer = new Cryptographer();
    }

    @Override
    public void run() {
        while (isActive) {
            try {
                int count;
                byte[] buffer;

                if(!isReceivingFile) {
                    buffer = new byte[inputStream.available()];
                } else {
                    buffer = new byte[inputStream.available()];
                }

                while ((count = inputStream.read(buffer)) > 0)
                {
                    byte[] decrypted = cryptographer.decrypt(buffer);
                    if(!isReceivingFile) {
                        handleInput(new String(decrypted));
                    } else {
                        if(fileHelper.getFileBytes().length == 0) {
                            fileHelper.setFileBytes(decrypted);
                        } else {
                            fileHelper.saveFile();
                            isReceivingFile = false;
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }

    }

    /**
     * Handle the user input form the console.
     * @param input user input from console
     */
    private void handleInput(String input) {
        try {
            if (input.equals("PING")) { // If we get a PING message we send back a PONG message.
                messageSender.send("PONG");
            } else if (input.contains("FILE")) {
                setupFileAccept(input);
                isReceivingFile = true;
            } else {
                System.out.println(input);
            }
        } catch (Exception ex) {
            isActive = false;
        }
    }

    /**
     * Setup the file helper for the client that's going to receive a file.
     * @param line command
     */
    private void setupFileAccept(String line) {
        String[] args = line.split(" ");
        if(args[0].equals("FILE")) {
            fileHelper = new ClientFileHelper(args[1], Integer.valueOf(args[2]));
        }
    }
}

ConnectionThread 也有类似的读取功能,如下所示:

while (isActive) {
        try {
            int count;
            byte[] buffer;

            if(!isReceivingFile) {
                buffer = new byte[inputStream.available()];
            } else {
                buffer = fileHelper.getFileBytes();
            }

            while ((count = inputStream.read(buffer)) > 0)
            {
                byte[] decrypted = server.cryptographer.decrypt(buffer);
                if(!isReceivingFile) {
                    getInput(new String(decrypted));
                } else {
                    fileHelper.setFileBytes(decrypted);
                    // bytes received, now we can send the file!
                    if(fileHelper.sendToReceiver()) {
                        writeToClient(fileHelper.getReceiverName()
                                + " received " + fileHelper.getFilename());
                        fileHelper = null;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            break;
        }
    }

在这种情况下,只需假设服务器 class 已正确初始化密码器 属性,情况总是如此。

我的猜测是某个值在某个地方做错了什么,但我不确定。我对我应该做什么来解决这个问题一无所知。有人可以帮我指出错误并提出解决此问题的可能解决方案吗?我的 java 版本是 12.0.1

我鼓励考虑使用 SSL/TLS 或 DTLS,而不是尝试重新实现它的一部分。

我不确定它是否会导致您的错误,但如果我对 Java documentation 的解释是正确的,那么您应该为每条消息更改 GCMParameterSpec:

after each encryption operation using GCM mode, callers should re-initialize the cipher objects with GCM parameters which has a different IV value

和:

GCM mode has a uniqueness requirement on IVs used in encryption with a given key. When IVs are repeated for GCM encryption, such usages are subject to forgery attacks.

此外,您没有使用 updateAAD(附加身份验证数据),尽管根据 https://www.rfc-editor.org/rfc/rfc5084 从错误消息中可以看出这是可选的,但它听起来像是在这里导致错误,但它可能只是一个误导性错误留言。

更新:

我为 Cryptographer class 写了很多单元测试,只有在我再次解密之前开始对密文进行随机更改时,我才会经常遇到同样的错误。因为我们可以相信 TCP/IP 在连接的另一端重现完全相同的字节,所以我们可能会遇到这些问题:

  1. 并发
  2. 将密文字节转换为字符串、字符、Readers/Writers
  3. 没有从套接字中读取整个消息(您是否检查了发送的字节数并将其与收到的字节数进行比较?

不,我还没有编写和测试我自己的实现,但是有一些例子,比如 this example, nicely explained by the author here from the code was found by this search

感谢 JohannesB 为我指明了正确的方向!

我现在已经解决了我的问题。它首先由阅读方法开始,我不得不更改为:

byte[] buffer;

while (inputStream.available() > 0)
{
    int read = inputStream.read(buffer);
    if(read == 0)
        break;
}
// An if statement checking if the buffer has been filled and based on this
// It will execute methods

我的密码学家 class 现在看起来像这样:

public class Cryptographer {
    private SecretKey secretKey;
    private byte[] aad;
    private SecureRandom secureRandom;
    private byte[] IV;

    public Cryptographer(SecretKey secretKey) {
        this.secretKey = secretKey;
        secureRandom = new SecureRandom();
        IV = new byte[12];
        secureRandom.nextBytes(IV);
        aad = "association".getBytes();
    }

    /**
     * Encrypt data.
     * @param data to encrypt
     * @return encrypted data
     */
    public byte[] encrypt(byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
            secureRandom.nextBytes(IV);
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
            cipher.updateAAD(aad);
            return toByteBuffer(cipher.doFinal(data));
        } catch (InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | NoSuchPaddingException
                | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Decrypt data.
     * @param data to decrypt
     * @return decrypted data
     */
    public byte[] decrypt(byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
            // get the data from the byte buffer
            data = fromByteBuffer(data);
            // create the gcm parameter with the received IV.
            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV);

            cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
            cipher.updateAAD(aad);
            return cipher.doFinal(data);
        } catch (InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | NoSuchPaddingException
                | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Put the encrypted data through a byte buffer.
     * This buffer will contain information about the IV array.
     * @param data encrypted data
     * @return the ByteBuffer result as byte array
     */
    private byte[] toByteBuffer(byte[] data) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(4 + IV.length + data.length);
        byteBuffer.putInt(IV.length);
        byteBuffer.put(IV);
        byteBuffer.put(data);
        return byteBuffer.array();
    }

    /**
     * Gets data from a ByteBuffer and sets up data needed for decryption.
     * @param data ByteBuffer data as byte array
     * @return ByteBuffer encrypted data
     */
    private byte[] fromByteBuffer(byte[] data) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(data);

        int ivLength = byteBuffer.getInt();
        if(ivLength < 12 || ivLength >= 16) {
            throw new IllegalArgumentException("invalid iv length");
        }

        IV = new byte[ivLength];
        byteBuffer.get(IV);

        byte[] remaining = new byte[byteBuffer.remaining()];
        byteBuffer.get(remaining);

        return remaining;
    }
}

至于我这样做的原因你可以看看JohannesB的建议,看看这些文章:

https://proandroiddev.com/security-best-practices-symmetric-encryption-with-aes-in-java-7616beaaade9

How to read all of Inputstream in Server Socket JAVA