使用Bouncy Castle解密AES-OCB消息时触发mac校验失败异常
AES-OCB解密:Python正常运行但Kotlin/Bouncy Castle验证失败
我需要解密AES消息,使用Python的PyCryptodome库可正常实现解密,但在Kotlin/Java环境中无法成功。由于解密模式为OCB,而Java默认不支持该模式,因此使用Bouncy Castle库进行开发。
可正常运行的Python代码
from base64 import b64decode from Crypto.Cipher import AES def decrypt_aes_message(shared_key, encrypted_message): encrypted_msg = b64decode(encrypted_message["encryptedMessage"].encode()) tag = b64decode(encrypted_message["tag"].encode()) nonce = b64decode(encrypted_message["nonce"].encode()) cipher = AES.new(shared_key.encode(), AES.MODE_OCB, nonce=nonce) return cipher.decrypt_and_verify(encrypted_msg, tag).decode()
出错的Kotlin代码
import org.bouncycastle.crypto.engines.AESEngine import org.bouncycastle.crypto.modes.OCBBlockCipher import org.bouncycastle.crypto.params.AEADParameters import org.bouncycastle.crypto.params.KeyParameter import java.nio.charset.Charsets fun decryptAesMessage2(sharedKey: String, encryptedMessageData: Map<String, String>): ByteArray { val encryptedMessage = encryptedMessageData["encryptedMessage"]!!.utf8Base64Decode() val tag = encryptedMessageData["tag"]!!.utf8Base64Decode() val nonce = encryptedMessageData["nonce"]!!.utf8Base64Decode() val key = KeyParameter(sharedKey.toByteArray(Charsets.UTF_8)) val params = AEADParameters(key, tag.size * 8, nonce) val cipher = OCBBlockCipher(AESEngine(), AESEngine()) cipher.init(false, params) val out = ByteArray(cipher.getOutputSize(encryptedMessage.size)) var offset = cipher.processBytes(encryptedMessage, 0, encryptedMessage.size, out, 0) offset += cipher.doFinal(out, offset) // 此处抛出异常 return out }
上述Kotlin代码在执行cipher.doFinal时抛出异常:org.bouncycastle.crypto.InvalidCipherTextException: mac check in OCB failed
问题复现文件说明
相关复现文件包含:
- py_working_code.py:可运行的Python脚本,需先安装PyCryptodome,执行命令
pip install pycryptodome - bc-debug:复现问题的Gradle项目内容
内容的提问来源于stack exchange,提问作者Vinícius M. Freitas
相关产品推荐
相关产品推荐

