讓我解決你的問題 「的模式。」 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