Python Crypto.Cipher.AES.MODE_CBC Examples

The following are 30 code examples of Crypto.Cipher.AES.MODE_CBC(). 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: crypto.py    From ACE with Apache License 2.0 6 votes vote down vote up
def decrypt_chunk(chunk, password=None):
    """Decrypts the given encrypted chunk with the given password and returns the decrypted 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


    _buffer = io.BytesIO(chunk)
    original_size = struct.unpack('<Q', _buffer.read(struct.calcsize('Q')))[0]
    iv = _buffer.read(16)
    chunk = _buffer.read()

    #original_size = struct.unpack('<Q', chunk[0:struct.calcsize('Q')])[0]
    #iv = chunk[struct.calcsize('Q'):struct.calcsize('Q') + 16]
    #chunk = chunk[struct.calcsize('Q') + 16:]
    decryptor = AES.new(password, AES.MODE_CBC, iv)
    result = decryptor.decrypt(chunk)
    return result[:original_size] 
Example #2
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 #3
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 #4
Source File: cyphermain.py    From Cypher with GNU General Public License v3.0 6 votes vote down vote up
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):

    if not out_filename:
        out_filename = in_filename + '.crypt'

    iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = os.path.getsize(in_filename)

    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)

            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)

                outfile.write(encryptor.encrypt(chunk)) 
Example #5
Source File: decrypt.py    From Cypher with GNU General Public License v3.0 6 votes vote down vote up
def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):

    # Split .crypt extension to restore file format
    if not out_filename:
        out_filename = os.path.splitext(in_filename)[0]

    with open(in_filename, 'rb') as infile:
        origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
        iv = infile.read(16)
        decryptor = AES.new(key, AES.MODE_CBC, iv)

        with open(out_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))
	    
	    # Truncate file to original size
            outfile.truncate(origsize) 
Example #6
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 #7
Source File: crypto.py    From Python-Scripts with GNU General Public License v3.0 6 votes vote down vote up
def decrypt(key, filename):
	chunksize = 64 * 1024
	outputFile = filename.split('.hacklab')[0]


	with open(filename, 'rb') as infile:
		filesize = int(infile.read(16))
		IV = infile.read(16)
		decryptor = AES.new(key, AES.MODE_CBC, IV)

		with open(outputFile, 'wb') as outfile:

			while True:
				chunk = infile.read(chunksize)

				if len(chunk) == 0:
					break

				chunk = str(decryptor.decrypt(chunk))
				chunk = chunk.replace("0000hack1lab0000", "")
				outfile.write(chunk)
			outfile.truncate(filesize) 
Example #8
Source File: aes-file-decrypt.py    From Effective-Python-Penetration-Testing with MIT License 6 votes vote down vote up
def decrypt_file(key, filename, chunk_size=24*1024):
        
    output_filename = os.path.splitext(filename)[0]

    with open(filename, 'rb') as infile:
        origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
        iv = infile.read(16)
        decryptor = AES.new(key, AES.MODE_CBC, iv)

        with open(output_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunk_size)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))

            outfile.truncate(origsize) 
Example #9
Source File: domcachedump.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def decrypt_hash(edata, nlkm, ch, xp = True):
    if xp:
        hmac_md5 = HMAC.new(nlkm, ch)
        rc4key = hmac_md5.digest()

        rc4 = ARC4.new(rc4key)
        data = rc4.encrypt(edata)
    else:
        # based on  Based on code from http://lab.mediaservice.net/code/cachedump.rb
        aes = AES.new(nlkm[16:32], AES.MODE_CBC, ch)
        data = ""
        for i in range(0, len(edata), 16):
            buf = edata[i : i + 16]
            if len(buf) < 16:
                buf += (16 - len(buf)) * "\00"
            data += aes.decrypt(buf)
    return data 
Example #10
Source File: lsasecrets.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def decrypt_aes(secret, key):
    """
    Based on code from http://lab.mediaservice.net/code/cachedump.rb
    """
    sha = SHA256.new()
    sha.update(key)
    for _i in range(1, 1000 + 1):
        sha.update(secret[28:60])
    aeskey = sha.digest()

    data = ""
    for i in range(60, len(secret), 16):
        aes = AES.new(aeskey, AES.MODE_CBC, '\x00' * 16)
        buf = secret[i : i + 16]
        if len(buf) < 16:
            buf += (16 - len(buf)) * "\00"
        data += aes.decrypt(buf)

    return data 
Example #11
Source File: util.py    From OpenData with Apache License 2.0 6 votes vote down vote up
def aes_decrypt(key, iv, content):
    """
    AES解密
     key,iv使用同一个
    模式cbc
    去填充pkcs7
    :param key:
    :param content:
    :return:
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    # base64解码
    encrypt_bytes = base64.b64decode(content)
    # 解密
    decrypt_bytes = cipher.decrypt(encrypt_bytes)
    # 重新编码
    result = str(decrypt_bytes, encoding='utf8')
    # 去除填充内容
    result = pkcs7unpadding(result)
    return result 
Example #12
Source File: util.py    From OpenData with Apache License 2.0 6 votes vote down vote up
def aes_encrypt(key, iv, content):
    """
    AES加密
    key,iv使用同一个
    模式cbc
    填充pkcs7
    :param key: 密钥
    :param content: 加密内容
    :return:
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    # 处理明文
    content_padding = pkcs7padding(content)
    # 加密
    encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
    # 重新编码
    result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
    return result 
Example #13
Source File: pack.py    From fygimbal with MIT License 5 votes vote down vote up
def encryptBlocks(img):
	cyphertext = []
	for i in range(numBlocks(img)):
		block = img[i*1024:(i+1)*1024]
		cyphertext.append(AES.new(key, AES.MODE_CBC, iv).encrypt(block))
	return b''.join(cyphertext) 
Example #14
Source File: crypto.py    From Python-Scripts with GNU General Public License v3.0 5 votes vote down vote up
def encrypt(key, filename, ig):
	chunksize = 64*1024
	outputFile = filename+".hacklab"
	size = os.path.getsize(filename) #+ 16
	filesize = str(size).zfill(16)
	IV = Random.new().read(16)
	secret = "0000hack1lab0000"

	encryptor = AES.new(key, AES.MODE_CBC, IV)

	with open(filename, 'rb') as infile:
		with open(outputFile, 'wb') as outfile:
			outfile.write(filesize.encode('utf-8'))
			outfile.write(IV)
			if ig != 'True':
				outfile.write(encryptor.encrypt(secret))

			while True:
				chunk = infile.read(chunksize)

				if len(chunk) == 0:
					break
				elif len(chunk) % 16 != 0:
					chunk += b' ' * (16 - (len(chunk) % 16))

				outfile.write(encryptor.encrypt(chunk)) 
Example #15
Source File: gnome_keyring.py    From ITWSV with MIT License 5 votes vote down vote up
def __init__(self, stream):
            hash_iterations = 1234
            password = "x" * 8
            salt = "\0" * 8
            key, iv = generate_key(password, salt, hash_iterations)
            self.cipher = AES.new(key, AES.MODE_CBC, iv) 
Example #16
Source File: mtprotoproxy.py    From mtprotoproxy with MIT License 5 votes vote down vote up
def try_use_pycrypto_or_pycryptodome_module():
    from Crypto.Cipher import AES
    from Crypto.Util import Counter

    def create_aes_ctr(key, iv):
        ctr = Counter.new(128, initial_value=iv)
        return AES.new(key, AES.MODE_CTR, counter=ctr)

    def create_aes_cbc(key, iv):
        return AES.new(key, AES.MODE_CBC, iv)

    return create_aes_ctr, create_aes_cbc 
Example #17
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def decrypt(self, init_vector, ciphertext):
        """Decrypt a ciphertext"""
        cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
        return Padding.unpad(cipher.decrypt(ciphertext), 16) 
Example #18
Source File: unpack.py    From fygimbal with MIT License 5 votes vote down vote up
def decryptBlocks(offset, count, outfile):
    for i in range(count):
        block = infile[8+(offset+i)*1024:8+(offset+i+1)*1024]
        outfile.write(AES.new(key, AES.MODE_CBC, iv).decrypt(block)) 
Example #19
Source File: default_crypto.py    From plugin.video.netflix with MIT License 5 votes vote down vote up
def encrypt(self, plaintext, esn):
        """
        Encrypt the given Plaintext with the encryption key
        :param plaintext:
        :return: Serialized JSON String of the encryption Envelope
        """
        init_vector = get_random_bytes(16)
        cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
        ciphertext = base64.standard_b64encode(
            cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16))).decode('utf-8')
        encryption_envelope = {
            'ciphertext': ciphertext,
            'keyid': '_'.join((esn, str(self.sequence_number))),
            'sha256': 'AA==',
            'iv': base64.standard_b64encode(init_vector).decode('utf-8')
        }
        return json.dumps(encryption_envelope) 
Example #20
Source File: utils.py    From snapy with MIT License 5 votes vote down vote up
def decrypt_story(data, key, iv):
    akey = b64decode(key)
    aiv = b64decode(iv)
    cipher = AES.new(akey, AES.MODE_CBC, aiv)
    return cipher.decrypt(pkcs5_pad(data)) 
Example #21
Source File: client.py    From gdog with GNU General Public License v3.0 5 votes vote down vote up
def Encrypt(self, plainText):
        raw = self._pad(plainText)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw)) 
Example #22
Source File: crypto.py    From ACE with Apache License 2.0 5 votes vote down vote up
def decrypt(source_path, target_path=None, password=None):
    """Decrypts the given file at source_path with the given password and saves the results in target_path.
       If target_path is None then output will be sent to standard output.
       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

    with open(source_path, 'rb') as fp_in:
        original_size = struct.unpack('<Q', fp_in.read(struct.calcsize('Q')))[0]
        iv = fp_in.read(16)
        decryptor = AES.new(password, AES.MODE_CBC, iv)

        with open(target_path, 'wb') as fp_out:
            while True:
                chunk = fp_in.read(CHUNK_SIZE)
                if len(chunk) == 0:
                    break

                fp_out.write(decryptor.decrypt(chunk))

            fp_out.truncate(original_size) 
Example #23
Source File: crypto.py    From ACE with Apache License 2.0 5 votes vote down vote up
def encrypt(source_path, target_path, password=None):
    """Encrypts the given file at source_path with the given password and saves the results in target_path.
       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)
    file_size = os.path.getsize(source_path)

    with open(source_path, 'rb') as fp_in:
        with open(target_path, 'wb') as fp_out:
            fp_out.write(struct.pack('<Q', file_size))
            fp_out.write(iv)

            while True:
                chunk = fp_in.read(CHUNK_SIZE)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += b' ' * (16 - len(chunk) % 16)

                fp_out.write(encryptor.encrypt(chunk)) 
Example #24
Source File: 2.py    From OpenData with Apache License 2.0 5 votes vote down vote up
def decrypt_response(des_key, des_iv, aes_key, aes_iv, content):
    """
    AES解密
     key,iv使用同一个
    模式cbc
    去填充pkcs7
    :param key:
    :param content:
    :return:
    """
    aes = AES.new(aes_key, AES.MODE_CBC, aes_iv)
    des = DES.new(des_key, DES.MODE_CBC, des_iv)
    # base64解码
    encrypt_bytes = base64.b64decode(content)
    # 解密
    decrypt_bytes = des.decrypt(encrypt_bytes)
    decrypt_bytes = base64.b64decode(decrypt_bytes)
    #decrypt_bytes = pkcs7padding(decrypt_bytes.decode()).encode("utf8")
    decrypt_bytes = aes.decrypt(decrypt_bytes)

    #base64解码
    decrypt_bytes = base64.b64decode(decrypt_bytes)
    # 重新编码
    result = str(decrypt_bytes, encoding='utf8')
    # 去除填充内容
    #result = pkcs7unpadding(result)
    return result 
Example #25
Source File: 2.py    From OpenData with Apache License 2.0 5 votes vote down vote up
def aes_decrypt(key, iv, content):
    """
    AES解密
     key,iv使用同一个
    模式cbc
    去填充pkcs7
    :param key:
    :param content:
    :return:
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    # base64解码
    encrypt_bytes = base64.b64decode(content)
    # 解密
    decrypt_bytes = cipher.decrypt(encrypt_bytes)
    # 重新编码
    result = str(decrypt_bytes, encoding='utf8')
    # 去除填充内容
    result = pkcs7unpadding(result)
    return result 
Example #26
Source File: 2.py    From OpenData with Apache License 2.0 5 votes vote down vote up
def aes_encrypt(key, iv, content):
    """
    AES加密
    key,iv使用同一个
    模式cbc
    填充pkcs7
    :param key: 密钥
    :param content: 加密内容
    :return:
    """
    cipher = AES.new(key, AES.MODE_CBC, iv)
    # 处理明文
    content_padding = pkcs7padding(content)
    # 加密
    encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))
    # 重新编码
    result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
    return result 
Example #27
Source File: decrypter.py    From SafeInCloud with GNU General Public License v3.0 5 votes vote down vote up
def decrypt( self ):
        #print "@ Decrypting %s ..." % self.db_filename

        self.input = open( self.db_filename, 'rb' )

        magic  = self.__read_short()
        sver   = self.__read_byte()
        salt   = self.__read_bytearray()

        # print "  - [PBKDF2] Deriving first key ..."

        skey   = self.__derive( self.password, salt )
        iv     = self.__read_bytearray()
        cipher = AES.new( skey, AES.MODE_CBC, iv )
        salt2  = self.__read_bytearray()
        block  = self.__read_bytearray()
        decr   = cipher.decrypt(block)
        sub_fd = StringIO.StringIO(decr)
        iv2    = self.__read_bytearray( sub_fd )
        pass2  = self.__read_bytearray( sub_fd )
        check  = self.__read_bytearray( sub_fd )

        # print "  - [PBKDF2] Deriving second key ..."

        skey2  = self.__derive( pass2, salt2, 1000 )
        cipher = AES.new( pass2, AES.MODE_CBC, iv2 )
        data   = cipher.decrypt( self.input.read() )

        # print "@ Decompressing ..."
        decompressor = zlib.decompressobj()
        return decompressor.decompress(data) + decompressor.flush() 
Example #28
Source File: twistmoe.py    From anime-downloader with The Unlicense 5 votes vote down vote up
def decrypt(encrypted, passphrase):
    encrypted = base64.b64decode(encrypted)
    assert encrypted[0:8] == b"Salted__"
    salt = encrypted[8:16]
    key_iv = bytes_to_key(passphrase, salt, 32+16)
    key = key_iv[:32]
    iv = key_iv[32:]
    aes = AES.new(key, AES.MODE_CBC, iv)
    return unpad(aes.decrypt(encrypted[16:])) 
Example #29
Source File: mihome.py    From goodbye-mihome with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_key():
    """Get current gateway key"""
    cipher = AES.new(config.MIHOME_GATEWAY_PASSWORD, AES.MODE_CBC, IV)
    encrypted = cipher.encrypt(get_store().get('gateway_token'))
    return binascii.hexlify(encrypted) 
Example #30
Source File: onepass.py    From opvault with GNU General Public License v3.0 5 votes vote down vote up
def decrypt_data(key, initialization_vector, data):
        """Decrypt data"""
        cipher = AES.new(key, AES.MODE_CBC, initialization_vector)
        return cipher.decrypt(data)