本文整理汇总了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]