这是我在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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。