當前位置: 首頁>>代碼示例>>Python>>正文


Python AES.block_size方法代碼示例

本文整理匯總了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) 
開發者ID:gabfl,項目名稱:vault,代碼行數:27,代碼來源:Encryption.py

示例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 
開發者ID:mortcanty,項目名稱:earthengine,代碼行數:19,代碼來源:FortunaGenerator.py

示例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 
開發者ID:PKUJohnson,項目名稱:OpenData,代碼行數:18,代碼來源:2.py

示例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 
開發者ID:IntegralDefense,項目名稱:ACE,代碼行數:23,代碼來源:crypto.py

示例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') 
開發者ID:CastagnaIT,項目名稱:plugin.video.netflix,代碼行數:24,代碼來源:credentials.py

示例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 
開發者ID:CastagnaIT,項目名稱:plugin.video.netflix,代碼行數:25,代碼來源:credentials.py

示例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. 
開發者ID:mtingers,項目名稱:backblaze-b2,代碼行數:22,代碼來源:backblazeb2.py

示例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 
開發者ID:mtingers,項目名稱:backblaze-b2,代碼行數:21,代碼來源:backblazeb2.py

示例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') 
開發者ID:Lamden,項目名稱:clove,代碼行數:18,代碼來源:wallet.py

示例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() 
開發者ID:jaraco,項目名稱:keyrings.alt,代碼行數:18,代碼來源:file.py

示例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 
開發者ID:artikrh,項目名稱:HackTheBox,代碼行數:20,代碼來源:crypto.py

示例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 
開發者ID:artikrh,項目名稱:HackTheBox,代碼行數:19,代碼來源:crypto.py

示例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)

    #----------------------------------------------------------- 
開發者ID:Arno0x,項目名稱:WSC2,代碼行數:20,代碼來源:crypto.py

示例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) 
開發者ID:gabfl,項目名稱:vault,代碼行數:5,代碼來源:test_Encryption.py

示例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] 
開發者ID:gabfl,項目名稱:vault,代碼行數:31,代碼來源:Encryption.py


注:本文中的Crypto.Cipher.AES.block_size方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。