kotlin - 如何使用 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))
}
解决方案
推荐阅读
- android - 如何使用 ViewPager 在特定页面上实现水平和垂直过渡?
- amazon-cloudformation - 使用 AWS Cloudformation 配置具有 SNS 主题的 CloudTrail
- json - 如何在 AWK 中打印 JSON 对象
- assembly - 这相当于 ret 指令吗?
- security - 一个数据库的多个站点和身份验证
- kotlin - Kotlin 替换字符串中的多个单词
- apache-spark - 在 Kubernetes 上运行 spark 的文件访问错误
- java - Spring 自定义范围生命周期 Bean 终止
- javascript - 关闭模态时如何从模态体中删除内容?
- php - 将 MySQL 数据加载到相应的 PHP 变量中