Ruby OpenSSL AES-128-CCM因auth_data而失败



我正在实现一个协议,根据规范,我需要使用AES-128-CCM和AES-128-GCM加密/解密数据我的问题是:在指定密码#auth_data时,如何使用CCM模式?我在网上找到的所有例子都使用GCM模式,这似乎有效,而CCM则不然。我遇到的例外是一个非常通用的OpenSSL::Cipher::CipherError,没有其他详细信息。

algo是选项(AES-128-CCM或AES-128-GCM(,并且没有auth_data是nil时,或者当algo是AES-128-GC并且auth_data不是nil时,我下面的示例代码可以工作。

我使用的是Ruby v2.5.5和OpenSSL v2.1.2。

algo = 'AES-128-CCM'  # AES-128-GCM works
auth_data = OpenSSL::Random.random_bytes(32) # nil works
cipher = OpenSSL::Cipher.new(algo).encrypt
if algo == 'AES-128-CCM'
cipher.auth_tag_len = 16
cipher.iv_len = 11
elsif algo == 'AES-128-GCM'
cipher.iv_len = 12
end
key = cipher.random_key
iv = cipher.random_iv
# has to be done in this order for unknown reasons
if algo == 'AES-128-CCM'
encrypted = cipher.update('Hello World') + cipher.final
cipher.auth_data = auth_data unless auth_data.nil?
elsif algo == 'AES-128-GCM'
cipher.auth_data = auth_data unless auth_data.nil?
encrypted = cipher.update('Hello World') + cipher.final
end
auth_tag = cipher.auth_tag
cipher = OpenSSL::Cipher.new(algo).decrypt
if algo == 'AES-128-CCM'
cipher.auth_tag_len = 16
cipher.iv_len = 11
elsif algo == 'AES-128-GCM'
cipher.iv_len = 12
end
cipher.key = key
cipher.iv = iv
cipher.auth_tag = auth_tag
cipher.update(encrypted)  # crashes when auth_data != nil and algo == AES-128-CCM

您已经在CCM调用中切换了身份验证数据和明文的顺序。

encrypted = cipher.update('Hello World') + cipher.final
cipher.auth_data = auth_data unless auth_data.nil?

通常,需要在明文数据之前处理附加的已验证数据。对于GCM(可能实现也可能不实现(,但对于CCM,有一些技巧。EAX模式确实允许任何顺序的参数,因为它被明确地设计为身份验证密码的更灵活的实现。

最新更新