【问题标题】:How should I implement an initialization vector to CBC code?我应该如何为 CBC 代码实现初始化向量?
【发布时间】:2021-09-23 22:47:35
【问题描述】:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend


key = b'InformationSecurity M.Sc'
message =   b"""yeahcourse snake"""
IV = '000102030405060708090a0b0c0d0e0f'
aesCipher = Cipher(algorithms.AES(key),
                   modes.CBC(),
                   backend=default_backend())
aesEncryptor = aesCipher.encryptor()
aesDecryptor = aesCipher.decryptor()

    
message += b"E" * (-len(message) % 16) # Padding to full blocks of 16 bytes 
ciphertext = aesEncryptor.update(message)

print("plaintext:",message)
print("ciphertext:",ciphertext.hex()) 
decryptedMessage = aesDecryptor.update(ciphertext)
print("recovered:",decryptedMessage)

一直是 ECB 模式,但现在想将其更改为 CBC 模式。当 aes 运行代码时,它会显示以下消息:

TypeError: __init__() missing 1 required positional argument: 'initialization_vector'

【问题讨论】:

  • 提问时请贴出整个回溯。

标签: python aes cbc-mode


【解决方案1】:

看起来一切都在文档中进行了描述:https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/

从文档中,它应该是“modes.CBC(IV)”。你错过了那个论点。

【讨论】:

  • 确保使用os.urandom(16) 之类的方式获取所述IV;如果将来使用相同的 IV 和相同的密钥,非随机 IV 会增加信息泄露的风险。
  • Alex:我建议在这里引用相关信息;页面会随着时间的推移而移动,并且您希望答案在发生这种情况时保持相关/有用。
  • 我在手机上打字,格式有点难)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多