首页 > 解决方案 > 如何使用 GCM 模式将 mac 标签添加到 AES

问题描述

我使用 bouncycastle 创建了一个加密方案,如下所示:

fun enc(plaintext : ByteArray, key : Key,iv : ByteArray) : ByteArray{
    val cipher : Cipher = Cipher.getInstance("AES/GCM/NOPADDING  ")

    cipher.init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(iv))
    return cipher.doFinal(plaintext)
}

fun dec(ciphertext : ByteArray, key: Key, iv : ByteArray) : String {
    val cipher : Cipher = Cipher.getInstance("AES/GCM/NOPADDING ")
    cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
    return String(cipher.doFinal(ciphertext))
}

然后我使用这个驱动程序代码来运行东西:

Security.addProvider(BouncyCastleFipsProvider())
val key2 : Key = SecretKeySpec(Hex.decode("e6d4d9472cf9b7a92a652fc7e1f3b4124906cff47f42115d77d64709f2177503"), "AES")

val iv : ByteArray =    Hex.decode("a2d21879269610eab7c16250b3b4bd81fc41b99738d7f8f2966ecd0bb2e5682a")


val ciphertext  =  encTWO("12345678123456781234567812345678".toByteArray(), key2, iv)
val decryptedText = decTWO(a, key2,iv)

println(Hex.toHexString(ciphertext))
print(decryptedText)

我需要添加一个标签(我知道这是一个mac),最好是128位添加到这个方案中,但我真的不知道怎么做?文档非常稀疏,我找不到任何示例

编辑:

我现在明白发送了 mac 标签,连接到密文的末尾,我有这些:

fun encGCM(plaintext : ByteArray, key : Key,iv : ByteArray) : ByteArray{
    val cipher : Cipher = Cipher.getInstance("AES/GCM/NOPADDING  ")

    val keyBytes : ByteArray = ByteArray(keylength)
    random.nextBytes(keyBytes)
    val macspec : GCMParameterSpec = GCMParameterSpec(128, iv )
    cipher.init(Cipher.ENCRYPT_MODE, key, macspec)
    return cipher.doFinal(plaintext)
}

fun decGCM(ciphertext : ByteArray, key: Key, iv : ByteArray) : String {
    val cipher : Cipher = Cipher.getInstance("AES/GCM/NOPADDING ")
    val macspec : GCMParameterSpec = GCMParameterSpec(128, iv )

    cipher.init(Cipher.DECRYPT_MODE, key, macspec)
    return String(cipher.doFinal(ciphertext))

}

标签: kotlinencryptionbouncycastle

解决方案


推荐阅读