让我解决你的问题 “的模式。” AES256是一种分组密码。它需要输入一个32字节的密钥和一个16字节的字符串,称为块并输出一个块。为了加密,我们在操作模式中使用AES。上面的解决方案建议使用CBC,这是一个例子。另一个称为CTR,它使用起来有些简单:
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
# AES supports multiple key sizes: 16 (AES128), 24 (AES192), or 32 (AES256).
key_bytes = 32
# Takes as input a 32-byte key and an arbitrary-length plaintext and returns a
# pair (iv, ciphtertext). "iv" stands for initialization vector.
def encrypt(key, plaintext):
assert len(key) == key_bytes
# Choose a random, 16-byte IV.
iv = Random.new().read(AES.block_size)
# Convert the IV to a Python integer.
iv_int = int(binascii.hexlify(iv), 16)
# Create a new Counter object with IV = iv_int.
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Encrypt and return IV and ciphertext.
ciphertext = aes.encrypt(plaintext)
return (iv, ciphertext)
# Takes as input a 32-byte key, a 16-byte IV, and a ciphertext, and outputs the
# corresponding plaintext.
def decrypt(key, iv, ciphertext):
assert len(key) == key_bytes
# Initialize counter for decryption. iv should be the same as the output of
# encrypt().
iv_int = int(iv.encode('hex'), 16)
ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
# Create AES-CTR cipher.
aes = AES.new(key, AES.MODE_CTR, counter=ctr)
# Decrypt and return the plaintext.
plaintext = aes.decrypt(ciphertext)
return plaintext
(iv, ciphertext) = encrypt(key, 'hella')
print decrypt(key, iv, ciphertext)
这通常被称为AES-CTR。 我建议在使用AES-CBC和PyCrypto时慎用。原因是它要求您指定填充方案,如其他解决方案所示。一般来说,如果你不是很细心的填充,还有attacks那个完全破解加密!
现在,重要的是要注意,密钥必须是随机的32字节字符串;密码不需要就够了。通常情况下,关键是像这样产生的:
# Nominal way to generate a fresh key. This calls the system's random number
# generator (RNG).
key1 = Random.new().read(key_bytes)
可将钥匙从密码,也得出:
# It's also possible to derive a key from a password, but it's important that
# the password have high entropy, meaning difficult to predict.
password = "This is a rather weak password."
# For added # security, we add a "salt", which increases the entropy.
#
# In this example, we use the same RNG to produce the salt that we used to
# produce key1.
salt_bytes = 8
salt = Random.new().read(salt_bytes)
# Stands for "Password-based key derivation function 2"
key2 = PBKDF2(password, salt, key_bytes)
一些解决方案上面的建议使用SHA256推导的关键,但这是一般认为是bad cryptographic practice。 查看wikipedia了解更多关于操作模式的信息。
[os.urandom](http://docs.python.org/3/library/os.html)被_encouraged_上的[PyCrypto](https://www.dlitz.net/software/pycrypto/)网站。它使用Microsoft的[CryptGenRandom](http://msdn.microsoft.com/en-us/library/windows/desktop/aa379942(V = vs.85)的.aspx)函数,它是一个[CSPRNG](HTTP:// en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) –
或'的/ dev/urandom'在Unix –
只是为了澄清,在该示例** **密码是其可以是128,192,或256位(16,24的_key_ ,或32个字节) – Mark