本文整理匯總了Python中Crypto.Cipher.AES.block_size方法的典型用法代碼示例。如果您正苦於以下問題:Python AES.block_size方法的具體用法?Python AES.block_size怎麽用?Python AES.block_size使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Crypto.Cipher.AES
的用法示例。
在下文中一共展示了AES.block_size方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: encrypt
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def encrypt(self, secret):
"""
Encrypt a secret
"""
# generate IV
IV = CryptoRandom.new().read(AES.block_size)
# Retrieve AES instance
aes = self.get_aes(IV)
# calculate needed padding
padding = AES.block_size - len(secret) % AES.block_size
# Python 2.x: secret += chr(padding) * padding
secret += bytes([padding]) * padding
# store the IV at the beginning and encrypt
data = IV + aes.encrypt(secret)
# Reset salted key
self.set_salt()
# Return base 64 encoded bytes
return base64.b64encode(data)
示例2: _pseudo_random_data
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def _pseudo_random_data(self, bytes):
if not (0 <= bytes <= self.max_bytes_per_request):
raise AssertionError("You cannot ask for more than 1 MiB of data per request")
num_blocks = ceil_shift(bytes, self.block_size_shift) # num_blocks = ceil(bytes / self.block_size)
# Compute the output
retval = self._generate_blocks(num_blocks)[:bytes]
# Switch to a new key to avoid later compromises of this output (i.e.
# state compromise extension attacks)
self._set_key(self._generate_blocks(self.blocks_per_key))
assert len(retval) == bytes
assert len(self.key) == self.key_size
return retval
示例3: pkcs7padding
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def pkcs7padding(text):
"""
明文使用PKCS7填充
最終調用AES加密方法時,傳入的是一個byte數組,要求是16的整數倍,因此需要對明文進行處理
:param text: 待加密內容(明文)
:return:
"""
bs = AES.block_size # 16
length = len(text)
bytes_length = len(bytes(text, encoding='utf-8'))
# tips:utf-8編碼時,英文占1個byte,而中文占3個byte
padding_size = length if(bytes_length == length) else bytes_length
padding = bs - padding_size % bs
# tips:chr(padding)看與其它語言的約定,有的會使用'\0'
padding_text = chr(padding) * padding
return text + padding_text
示例4: encrypt_chunk
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def encrypt_chunk(chunk, password=None):
"""Encrypts the given chunk of data and returns the encrypted chunk.
If password is None then saq.ENCRYPTION_PASSWORD is used instead.
password must be a byte string 32 bytes in length."""
if password is None:
password = saq.ENCRYPTION_PASSWORD
assert isinstance(password, bytes)
assert len(password) == 32
iv = Crypto.Random.OSRNG.posix.new().read(AES.block_size)
encryptor = AES.new(password, AES.MODE_CBC, iv)
original_size = len(chunk)
if len(chunk) % 16 != 0:
chunk += b' ' * (16 - len(chunk) % 16)
result = struct.pack('<Q', original_size) + iv + encryptor.encrypt(chunk)
return result
示例5: encrypt_credential
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def encrypt_credential(raw):
"""
Encodes data
:param data: Data to be encoded
:type data: str
:returns: string -- Encoded data
"""
# pylint: disable=invalid-name,import-error
import base64
try: # The crypto package depends on the library installed (see Wiki)
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util import Padding
except ImportError:
from Cryptodome import Random
from Cryptodome.Cipher import AES
from Cryptodome.Util import Padding
raw = bytes(Padding.pad(data_to_pad=raw.encode('utf-8'), block_size=__BLOCK_SIZE__))
iv = Random.new().read(AES.block_size)
cipher = AES.new(get_crypt_key(), AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8')
示例6: decrypt_credential
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def decrypt_credential(enc, secret=None):
"""
Decodes data
:param data: Data to be decoded
:type data: str
:returns: string -- Decoded data
"""
# pylint: disable=invalid-name,import-error
import base64
try: # The crypto package depends on the library installed (see Wiki)
from Crypto.Cipher import AES
from Crypto.Util import Padding
except ImportError:
from Cryptodome.Cipher import AES
from Cryptodome.Util import Padding
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(secret or get_crypt_key(), AES.MODE_CBC, iv)
decoded = Padding.unpad(
padded_data=cipher.decrypt(enc[AES.block_size:]),
block_size=__BLOCK_SIZE__)
return decoded
示例7: decrypt
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def decrypt(in_file, out_file, password, key_length=32):
bs = AES.block_size
salt = in_file.read(bs)[len('Salted__'):]
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
next_chunk = ''
finished = False
while not finished:
chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
if len(next_chunk) == 0:
padding_length = ord(chunk[-1])
chunk = chunk[:-padding_length]
finished = True
out_file.write(chunk)
# A stupid way to calculate size of encrypted file and sha1
# B2 requires a header with the sha1 but urllib2 must have the header before streaming
# the data. This means we must read the file once to calculate the sha1, then read it again
# for streaming the data on upload.
示例8: calc_encryption_sha_and_length
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def calc_encryption_sha_and_length(in_file, password, salt, key_length, key,
iv):
bs = AES.block_size
size = 0
cipher = AES.new(key, AES.MODE_CBC, iv)
sha = hashlib.sha1()
sha.update('Salted__' + salt)
size += len('Salted__' + salt)
finished = False
while not finished:
chunk = in_file.read(1024 * bs)
if len(chunk) == 0 or len(chunk) % bs != 0:
padding_length = (bs - len(chunk) % bs) or bs
chunk += padding_length * chr(padding_length)
finished = True
chunk = cipher.encrypt(chunk)
sha.update(chunk)
size += len(chunk)
return sha.hexdigest(), size
示例9: decrypt_private_key
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def decrypt_private_key(encrypted_private_key: bytes, password: str) -> str:
'''
Decrypt private key with the password.
Args:
encrypted_private_key (bytes): encrypted private key
password (str): password to decrypt private key with
Returns:
str: decrypted private key
'''
encrypted_private_key = base64.b64decode(encrypted_private_key)
iv = encrypted_private_key[:AES.block_size]
cipher = AES.new(sha256(bytes(password.encode('utf-8'))).digest(), AES.MODE_CFB, iv)
private_key = cipher.decrypt(encrypted_private_key[AES.block_size:])
return str(private_key, 'ascii')
示例10: encrypt
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def encrypt(self, password, assoc=None):
# encrypt password, ignore associated data
from Crypto.Random import get_random_bytes
salt = get_random_bytes(self.block_size)
from Crypto.Cipher import AES
IV = get_random_bytes(AES.block_size)
cipher = self._create_cipher(self.keyring_key, salt, IV)
password_encrypted = cipher.encrypt(self.pw_prefix + password)
# Serialize the salt, IV, and encrypted password in a secure format
data = dict(salt=salt, IV=IV, password_encrypted=password_encrypted)
for key in data:
# spare a few bytes: throw away newline from base64 encoding
data[key] = encodebytes(data[key]).decode()[:-1]
return json.dumps(data).encode()
示例11: encrypt
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def encrypt(plaintext, key):
"""
Encrypt the plaintext with AES method.
Parameters:
plaintext -- String to be encrypted.
key -- Key for encryption.
"""
iv = Random.new().read(AES.block_size)
cipher = AES.new(pad(key), AES.MODE_CFB, iv)
# If user has entered non ascii password (Python2)
# we have to encode it first
if hasattr(str, 'decode'):
plaintext = plaintext.encode('utf-8')
encrypted = base64.b64encode(iv + cipher.encrypt(plaintext))
return encrypted
示例12: decrypt
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def decrypt(ciphertext, key):
"""
Decrypt the AES encrypted string.
Parameters:
ciphertext -- Encrypted string with AES method.
key -- key to decrypt the encrypted string.
"""
global padding_string
ciphertext = base64.b64decode(ciphertext)
iv = ciphertext[:AES.block_size]
cipher = AES.new(pad(key), AES.MODE_CFB, iv)
decrypted = cipher.decrypt(ciphertext[AES.block_size:])
return decrypted
示例13: encryptData
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def encryptData(cls, clearText, key):
"""Encrypts data with the provided key.
The returned byte array is as follow:
:==============:==================================================:
: IV (16bytes) : Encrypted (data + PKCS7 padding information) :
:==============:==================================================:
"""
# Generate a crypto secure random Initialization Vector
iv = urandom(AES.block_size)
# Perform PKCS7 padding so that clearText is a multiple of the block size
clearText = cls.pad(clearText)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(clearText)
#-----------------------------------------------------------
示例14: test_get_aes
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def test_get_aes(self):
IV = CryptoRandom.new().read(AES.block_size)
self.assertIsInstance(self.enc2.get_aes(IV), Cipher._mode_cbc.CbcMode)
示例15: decrypt
# 需要導入模塊: from Crypto.Cipher import AES [as 別名]
# 或者: from Crypto.Cipher.AES import block_size [as 別名]
def decrypt(self, enc_secret):
"""
Decrypt a secret
"""
# Decode base 64
enc_secret = base64.b64decode(enc_secret)
# extract the IV from the beginning
IV = enc_secret[:AES.block_size]
# Retrieve AES instance
aes = self.get_aes(IV)
# Decrypt
data = aes.decrypt(enc_secret[AES.block_size:])
# pick the padding value from the end; Python 2.x: ord(data[-1])
padding = data[-1]
# Python 2.x: chr(padding) * padding
if data[-padding:] != bytes([padding]) * padding:
raise ValueError("Invalid padding...")
# Reset salted key
self.set_salt()
# Remove the padding and return the bytes
return data[:-padding]