Closed. This question is not reproducible or was caused by typos。它当前不接受答案。
                        
                    
                
            
        
            
        
                
                    
                
            
                
                    想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                
                    2个月前关闭。
            
        

    

我有一种解密数据的方法:

private byte[] decrypt(byte[] sessionKey, byte[] initialisationVector, byte[] associatedData, byte[] cipherText, byte[] tag) {
    Key secret = new SecretKeySpec(sessionKey, "AES");

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, secret,
                new GCMParameterSpec((GCM_AUTHENTICATION_TAG_SIZE) * Byte.SIZE, initialisationVector));
    cipher.updateAAD(associatedData);

    return cipher.doFinal(concatByteArrays(cipherText, tag));
}


concatByteArrays是带有Bytebuffer.allocate.put方法的简单方法。
UPD:输入-

    byte[] TEST_AES_KEY = new byte[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    int INITIALISATION_VECTOR_LENGTH = 12;
    int GCM_AUTHENTICATION_TAG_SIZE = 16;
    byte[] initialisationVector = Arrays.copyOfRange(receivedPacket, 0, INITIALISATION_VECTOR_LENGTH - 1);
    byte[] tag = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE - 1);
    byte[] associatedData = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE, receivedPacket.length - 1);
    byte[] cipherText = new byte[]{};


byte[] plainText = decrypt(key, initialisationVector, associatedData, cipherText, tag);


但是得到错误:

javax.crypto.AEADBadTagException: Input too short - need tag
        at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterM
ode.java:524)
        at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:104
8)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:985)
        at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
        at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
        at javax.crypto.Cipher.doFinal(Cipher.java:2164)


我不明白如何传递标签。
我有一个python代码,它可以工作:

decryptor = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend).decryptor()

decryptor.authenticate_additional_data(aad)

return decryptor.update(ciphertext) + decryptor.finalize()

最佳答案

愚蠢的错误。我忘记了arrays.copyof中的最后一个参数是互斥的,并且从receivePacket获取了错误的字节数组。

    byte[] initialisationVector = Arrays.copyOfRange(receivedPacket, 0, INITIALISATION_VECTOR_LENGTH);
    byte[] tag = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE);
    byte[] associatedData = Arrays.copyOfRange(receivedPacket, INITIALISATION_VECTOR_LENGTH + GCM_AUTHENTICATION_TAG_SIZE, receivedPacket.length);

07-28 13:05