开发者社区> 问答> 正文

Python aes ctr(密码学)。相似的输入给出相似的输出

这是我在Python中使用密码学实现的AES-256-CTR。有害物质模块:

from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CTR
from cryptography.hazmat.backends import default_backend as backend
from base58 import b58encode,b58decode
import os

class AESCipher:
  def __init__(self,key):
    self.counter = 0
    self.key = key

    #AES 256 Requirement
    assert len(self.key) == 32

  def encrypt(self,plain_text):
    plain_text = plain_text.encode()
    self.counter += 1
    cipher = Cipher(AES(self.key),CTR(self.padCounter()),backend())
    encryption_engine = cipher.encryptor()
    cipher_text = self.padCounter() + encryption_engine.update(plain_text) + encryption_engine.finalize()
    return b58encode(cipher_text)

  def decrypt(self,cipher_text):
    cipher_text = b58decode(cipher_text)
    self.counter = cipher_text[:16]
    cipher = Cipher(AES(self.key),CTR(self.counter),backend())
    decryption_engine = cipher.decryptor()
    plain_text = decryption_engine.update(cipher_text[16:]) + decryption_engine.finalize()
    return plain_text.decode()

  def padCounter(self):
    return bytes(str(self.counter).zfill(16),"ascii")

当我加密类似的消息,我得到类似的输出:

>>> key = os.urandom(32)
>>> a = AESCipher(key)
>>> a.encrypt("message to encrypt one")
b'88SwQ7r6DKsuejgkEnxmGcQqjDdNAgd6vFZ7WLNB4oHBiqnxErpj'
>>> a.encrypt("message to encrypt two")
b'88SwQ7r6DKsuejgkEnxmGdKfTyyABe2JjpgbUK3poe2thiLGw5Et'
>>> a.encrypt("message to encrypt three")
b'3Psbq3enwAmwXGa2QejWFeyK8HS4DWCQrqSrWHxxbRzUsaYnYuKqEFZ'
>>> a.encrypt("message to encrypt four")
b'YTsV73Dg1QKhPZQRqss8QDKp7R2tgc3hShj5rdb911DeEqG1Jr4v9'
>>> a.encrypt("message to encrypt five")
b'YTsV73Dg1QKhPZQRqss8QJsVauew5vWjVEbEuvXufkmorxW46a44w'
>>> a.encrypt("message to encrypt six")
b'88SwQ7r6DKsuejgkEnxmGi4NDfNPe1wZ5KfFFLk93p7jBAA8nvqv'
>>> 

密文的输出有很多相似之处,这是期望的行为,即计数器从00000000000到000000000000000,然后在异或运算中没有很多不同,还是我搞砸了AES的实现? 问题来源StackOverflow 地址:/questions/59378913/python-aes-ctr-cryptography-hazmat-aes-similar-inputs-gives-similar-outputs

展开
收起
kun坤 2019-12-30 09:58:41 607 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载