错误javax.crypto.AEADBadTagException:标记不匹配

时间:2018-04-03 22:49:06

标签: java kotlin aes aes-gcm

我在kotlin中使用AES / GCM / NoPadding加密(我对它很新)。如果我理解正确的GCM

javax.crypto.AEADBadTagException: Tag mismatch!
        at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:571)

代码程序:

fun proc_raw_packet(raw : ByteArray, client : Boolean = true)
{
    if (raw.isEmpty()) return
    var lastByte = raw.last().toInt() and 0xFF
    if (lastByte != 0) {
        if (EncryptionToken == "") {
            println("data noecod: " + Hex.encodeHexString(raw))

            var bitsize = (raw.size * 8) - 2
            while ((lastByte and 0x80) == 0) {
                lastByte *= 2
                bitsize--
            }
            val reader = Buffer(raw, 0, bitsize)

            reader.proc_raw_packet(client)
        } else {
            val reader1 = Buffer(raw)
            println("_______________________________________")




            try {
                println("hash: " + reader1.readBit())
                println("enc: " + reader1.readBit())
                val nonce = reader1.readBytes(12)
                println("nonce: " + Hex.encodeHexString(nonce) + " " + nonce.size)
                val tag = reader1.readBytes(16)
                println("tag: " + Hex.encodeHexString(tag) + " " + tag.size)
                val skeySpec = SecretKeySpec(Base64.decodeBase64(EncryptionToken), "AES")
                val cipher = Cipher.getInstance("AES/GCM/NoPadding")
                println("key: " + Base64.decodeBase64(EncryptionToken))
                val params = GCMParameterSpec(128, nonce)
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, params)

                val bitsleft = reader1.bitsLeft()
                val cipherBytes = reader1.readBits(bitsleft)

                cipher.update(cipherBytes)
                cipher.update(tag)
                val deCiphered = cipher.doFinal()
                println("deCiphered: " + Hex.encodeHexString(deCiphered))
                val reader11 =  Buffer(deCiphered, bitsleft)
                reader11.proc_raw_packetenct(client)
            } catch (e: Exception) {
                e.printStackTrace()
                throw RuntimeException("Failed to decrypt")
            }
            }
    }
}

我无法理解错误在哪里,就像一切都是真的 我尝试了不同,但它没有帮助 nonce:2f736462d76dc6d7d7714371 12 tagg:8c21176dd34b9a0dae9ad0045a8a074c 16

0 个答案:

没有答案