Python Crypto.Cipher.AES.block_size() Examples

The following are 30 code examples of Crypto.Cipher.AES.block_size(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Crypto.Cipher.AES , or try the search function .
Example #1
Source File: file.py    From keyrings.alt with MIT License 8 votes vote down vote up
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() 
Example #2
Source File: FortunaGenerator.py    From earthengine with MIT License 6 votes vote down vote up
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 
Example #3
Source File: crypto.py    From WSC2 with GNU General Public License v3.0 6 votes vote down vote up
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)

    #----------------------------------------------------------- 
Example #4
Source File: Encryption.py    From vault with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: 2.py    From OpenData with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: util.py    From OpenData with Apache License 2.0 6 votes vote down vote up
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 
Example #7
Source File: crypto.py    From ACE with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: credentials.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
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') 
Example #9
Source File: credentials.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
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 
Example #10
Source File: backblazeb2.py    From backblaze-b2 with MIT License 6 votes vote down vote up
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. 
Example #11
Source File: backblazeb2.py    From backblaze-b2 with MIT License 6 votes vote down vote up
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 
Example #12
Source File: FortunaGenerator.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #13
Source File: cred.py    From Medium_Grabber with MIT License 5 votes vote down vote up
def pad(self, s):
        return s + b"\0" * (AES.block_size - len(s) % AES.block_size) 
Example #14
Source File: aes_cipher.py    From jak with Apache License 2.0 5 votes vote down vote up
def __init__(self, key, mode=AES.MODE_CBC):
        """You can override the mode if you want, But you had better know
        what you are doing."""

        self.cipher = AES
        self.mode = mode
        self.BLOCK_SIZE = AES.block_size
        self.SIG_SIZE = SHA512.digest_size
        self.VERSION = 'JAK-000'

        # We force the key to be 64 hexdigits (nibbles) because we are sadists.
        key_issue_exception = JakException(
            ("Key must be 64 hexadecimal [0-f] characters long. \n"
             "jak recommends you use the 'keygen' command to generate a strong key."))

        # Long enough?
        if len(key) != 64:
            raise key_issue_exception

        try:
            self.key = binascii.unhexlify(key)
        except (TypeError, binascii.Error):

            # Not all of them are hexadecimals in all likelihood
            raise key_issue_exception

        # Generate a separate HMAC key. This is (to my understanding) not
        # strictly necessary.
        # But was recommended by Thomas Pornin (http://crypto.stackexchange.com/a/8086)
        self.hmac_key = SHA512.new(data=key.encode()).digest() 
Example #15
Source File: kmstool.py    From kmstool with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 key_id=None,
                 key_spec='AES_256',
                 temp_dir='/var/tmp/kmstool',
                 profile=None,
                 region=None,
                 key_length=32,):
        self.key_id=key_id
        self.key_spec=key_spec
        self.key_length=key_length
        self.bs = AES.block_size
        self.temp_dir = '{}/{}/'.format(temp_dir.rstrip('/\\'), uuid.uuid4())
        self.profile=profile
        self.region=region
        try: 
            makedirs(self.temp_dir)
        except:
            self.rm_rf(self.temp_dir)
            makedirs(self.temp_dir)
        self.enc_file = join(self.temp_dir, 'file.enc')
        self.cipher_file = join(self.temp_dir, 'key.enc')
        self.session = self.connect()
        self.kms = self.session.client('kms')
        self.s3 = self.session.client('s3')


    # walk a directory structure and remove everything 
Example #16
Source File: utils.py    From openprocurement.api with Apache License 2.0 5 votes vote down vote up
def encrypt(uuid, name, key):
    iv = "{:^{}.{}}".format(name, AES.block_size, AES.block_size)
    text = "{:^{}}".format(key, AES.block_size)
    return hexlify(AES.new(uuid, AES.MODE_CBC, iv).encrypt(text)) 
Example #17
Source File: test_client.py    From pina-colada with MIT License 5 votes vote down vote up
def encrypt(self, string, sock):
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.keys[sock], AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(pad(string))) 
Example #18
Source File: utils.py    From openprocurement.api with Apache License 2.0 5 votes vote down vote up
def decrypt(uuid, name, key):
    iv = "{:^{}.{}}".format(name, AES.block_size, AES.block_size)
    try:
        text = AES.new(uuid, AES.MODE_CBC, iv).decrypt(unhexlify(key)).strip()
    except:
        text = ''
    return text 
Example #19
Source File: client.py    From pina-colada with MIT License 5 votes vote down vote up
def encrypt(self, string, sock):
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.keys[sock], AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(pad(string))) 
Example #20
Source File: server.py    From pina-colada with MIT License 5 votes vote down vote up
def encrypt(self, string, c):
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.keys[c], AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(pad(string))) 
Example #21
Source File: sob.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _encrypt(passphrase, data):
    from Crypto.Cipher import AES as cipher

    warnings.warn(
        'Saving encrypted persisted data is deprecated since Twisted 15.5.0',
        DeprecationWarning, stacklevel=2)

    leftover = len(data) % cipher.block_size
    if leftover:
        data += b' ' * (cipher.block_size - leftover)
    return cipher.new(md5(passphrase).digest()[:16]).encrypt(data) 
Example #22
Source File: FortunaGenerator.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _generate_blocks(self, num_blocks):
        if self.key is None:
            raise AssertionError("generator must be seeded before use")
        assert 0 <= num_blocks <= self.max_blocks_per_request
        retval = []
        for i in xrange(num_blocks >> 12):      # xrange(num_blocks / 4096)
            retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros))
        remaining_bytes = (num_blocks & 4095) << self.block_size_shift  # (num_blocks % 4095) * self.block_size
        retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros[:remaining_bytes]))
        return b("").join(retval)

# vim:set ts=4 sw=4 sts=4 expandtab: 
Example #23
Source File: test_Encryption.py    From vault with MIT License 5 votes vote down vote up
def test_get_aes(self):
        IV = CryptoRandom.new().read(AES.block_size)
        self.assertIsInstance(self.enc2.get_aes(IV), Cipher._mode_cbc.CbcMode) 
Example #24
Source File: FortunaGenerator.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        self.counter = Counter.new(nbits=self.block_size*8, initial_value=0, little_endian=True)
        self.key = None

        # Set some helper constants
        self.block_size_shift = exact_log2(self.block_size)
        assert (1 << self.block_size_shift) == self.block_size

        self.blocks_per_key = exact_div(self.key_size, self.block_size)
        assert self.key_size == self.blocks_per_key * self.block_size

        self.max_bytes_per_request = self.max_blocks_per_request * self.block_size 
Example #25
Source File: ticket.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def issue( self ):
        """
        Returns a ready-to-use session ticket after prior initialisation.

        After the `SessionTicket()' class was initialised with a master key,
        this method encrypts and authenticates the protocol state and returns
        the final result which is ready to be sent over the wire.
        """

        self.state.issueDate = int(time.time())

        # Encrypt the protocol state.
        aes = AES.new(self.symmTicketKey, mode=AES.MODE_CBC, IV=self.IV)
        state = repr(self.state)
        assert (len(state) % AES.block_size) == 0
        cryptedState = aes.encrypt(state)

        # Authenticate the encrypted state and the IV.
        hmac = HMAC.new(self.hmacTicketKey,
                        self.IV + cryptedState, digestmod=SHA256).digest()

        finalTicket = self.IV + cryptedState + hmac
        log.debug("Returning %d-byte ticket." % len(finalTicket))

        return finalTicket


# Alias class name in order to provide a more intuitive API. 
Example #26
Source File: crypto.py    From streamlink with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def decrypt_openssl(data, passphrase, key_length=32):
    if data.startswith(b"Salted__"):
        salt = data[len(b"Salted__"):AES.block_size]
        key, iv = evp_bytestokey(passphrase, salt, key_length, AES.block_size)
        d = AES.new(key, AES.MODE_CBC, iv)
        out = d.decrypt(data[AES.block_size:])
        return unpad_pkcs5(out) 
Example #27
Source File: crypto.py    From WSC2 with GNU General Public License v3.0 5 votes vote down vote up
def decryptData(cls, cipherText, key):
		"""Decrypt data with the provided key"""

		# Initialization Vector is in the first 16 bytes
		iv = cipherText[:AES.block_size]

		cipher = AES.new(key, AES.MODE_CBC, iv)
		return cls.unpad(cipher.decrypt(cipherText[AES.block_size:]))

	#------------------------------------------------------------------------ 
Example #28
Source File: file.py    From keyrings.alt with MIT License 5 votes vote down vote up
def _create_cipher(self, password, salt, IV):
        """
        Create the cipher object to encrypt or decrypt a payload.
        """
        from Crypto.Protocol.KDF import PBKDF2
        from Crypto.Cipher import AES

        pw = PBKDF2(password, salt, dkLen=self.block_size)
        return AES.new(pw[: self.block_size], AES.MODE_CFB, IV) 
Example #29
Source File: wallet.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
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') 
Example #30
Source File: stage3.py    From nekros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pad(self, s):
        return s + b"\0" * (AES.block_size - len(s) % AES.block_size)