Python源码示例:Crypto.Cipher.AES.MODE_CBC

示例1
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) 
示例2
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)) 
示例3
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) 
示例4
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 
示例5
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 
示例6
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 
示例7
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 
示例8
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 
示例9
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] 
示例10
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) 
示例11
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') 
示例12
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 
示例13
def __init__(self, key, iv=None):
        iv = iv or key[:16]
        super().__init__(AES.new(key, AES.MODE_CBC, iv)) 
示例14
def encrypt(plaintext, key, blockSize):
	iv = bytearray(os.urandom(blockSize))
	iv = str(iv)
	reIV = bytearray(os.urandom(blockSize))
	reIV = str(reIV)
	rivPlaintext = pad(reIV + str(plaintext), blockSize)
	#print "rivPlaintext: " + base64.b64encode(rivPlaintext)
	cipher = AES.new(key, AES.MODE_CBC, IV=iv)
	return iv + str(cipher.encrypt(rivPlaintext)) 
示例15
def decrypt(ciphertext, key, blockSize):
	#print "ciphertext: " + base64.b64encode(ciphertext)
	iv = ciphertext[0:blockSize]
	#print "iv: " + base64.b64encode(iv)
	#print "ciphertext: " + base64.b64encode(ciphertext)
	rivCiphertext = ciphertext[blockSize:]
	#print "rivCiphertext: " + base64.b64encode(rivCiphertext)
	rivCiphertext = str(rivCiphertext)
	#print "rivCiphertext: " + base64.b64encode(rivCiphertext)
	cipher = AES.new(key, AES.MODE_CBC, IV=iv)
	rivPlaintext = cipher.decrypt(rivCiphertext)
	#print "rivPlaintext: " + base64.b64encode(rivPlaintext)
	rivPlaintext = str(rivPlaintext)
	#print "rivPlaintext: " + base64.b64encode(rivPlaintext)
	rivPlaintext = unpad(rivPlaintext)
	#print "rivPlaintext: " + base64.b64encode(rivPlaintext)
	#rivPlaintext = str(cipher.decrypt(str(rivCiphertext)))
	#print "rivPlaintext: " + base64.b64encode(rivPlaintext)
	#print "rivPlaintext: " + base64.b64encode(rivPlaintext[blockSize:])
	return rivPlaintext[blockSize:]
	#return rivPlaintext 
示例16
def get_aes(self, IV):
        """
            AES instance
        """

        return AES.new(self.digest_key(), AES.MODE_CBC, IV) 
示例17
def aes_encrypt(self, message, passphrase):
        IV = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        aes = AES.new(passphrase, AES.MODE_CBC, IV)
        return aes.encrypt(message)

    # get value used to build the salt 
示例18
def encrypt(self, key, msg):
        from Crypto.Cipher import AES
        secret = self.getSecret(key)
        Initial16bytes = '0123456789012345'
        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
        enc = encodestring(cipher.encrypt(self.pad(msg)))
        return enc 
示例19
def decrypt(self, key, msg):
        from Crypto.Cipher import AES
        try:
            secret = self.getSecret(key)
            Initial16bytes = '0123456789012345'
            cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
            plain = self.depad(cipher.decrypt(decodestring(msg)))
        except:
            return msg
        try:
            return eval(plain)
        except SyntaxError:
            return plain 
示例20
def encrypt(self, key, msg):
        from Crypto.Cipher import AES
        secret = self.getSecret(key)
        Initial16bytes = '0123456789012345'
        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
        return encodestring(
            cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8') 
示例21
def decrypt(self, key, msg):
        from Crypto.Cipher import AES
        secret = self.getSecret(key)
        Initial16bytes = '0123456789012345'
        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
        return (cipher.decrypt(
            decodestring(msg.encode('utf-8')))).decode('utf-8') 
示例22
def test_upload_source(bugbuzz_client, source_file):
    source, uploaded_file = source_file

    url = urlparse.urljoin(
        bugbuzz_client.base_url,
        '/files/{}'.format(uploaded_file['id']),
    )
    resp = requests.get(url)
    file_ = resp.json()['file']
    assert file_['session'] == bugbuzz_client.session_id

    iv = base64.b64decode(file_['aes_iv'].encode('latin1'))
    content = base64.b64decode(file_['content'].encode('latin1'))
    aes = AES.new(bugbuzz_client.aes_key, AES.MODE_CBC, iv)
    assert pkcs5_unpad(aes.decrypt(content)) == source 
示例23
def test_encrypt_decrypt(bugbuzz_client):
    plaintext = b'super foobar'
    iv, encrypted = bugbuzz_client.encrypt(plaintext)
    assert encrypted != plaintext

    aes = AES.new(bugbuzz_client.aes_key, AES.MODE_CBC, iv)
    assert pkcs5_unpad(aes.decrypt(encrypted)) == plaintext 
示例24
def encrypt(self, key, msg):
        from Crypto.Cipher import AES
        secret = self.getSecret(key)
        Initial16bytes = '0123456789012345'
        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
        enc = encodestring(cipher.encrypt(self.pad(msg)))
        return enc 
示例25
def decrypt(self, key, msg):
        from Crypto.Cipher import AES
        try:
            secret = self.getSecret(key)
            Initial16bytes = '0123456789012345'
            cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
            plain = self.depad(cipher.decrypt(decodestring(msg)))
        except:
            return msg
        try:
            return eval(plain)
        except SyntaxError:
            return plain 
示例26
def encrypt(self, key, msg):
        from Crypto.Cipher import AES
        secret = self.getSecret(key)
        Initial16bytes = '0123456789012345'
        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
        return encodestring(
            cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8') 
示例27
def decrypt(self, key, msg):
        from Crypto.Cipher import AES
        secret = self.getSecret(key)
        Initial16bytes = '0123456789012345'
        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
        return (cipher.decrypt(
            decodestring(msg.encode('utf-8')))).decode('utf-8') 
示例28
def decrypt_string(cipher, key):
    cipher = base64.b64decode(cipher)
    key = SHA256.new(key).digest()
    decryptor = AES.new(key, AES.MODE_CBC, global_IV)
    message = decryptor.decrypt(cipher)
    #TODO: implement more robust padding
    return message.rstrip() 
示例29
def encrypt_string(message, key):
    #message = 'this is my message'
    #TODO: implement more robust padding
    padding = (16 - (len(message) % 16))
    padded_message = message + ' ' * padding
    key = SHA256.new(key).digest()
    #IV = Random.new().read(AES.block_size)
    encryptor = AES.new(key, AES.MODE_CBC, global_IV)
    cipher = encryptor.encrypt(padded_message)
    return base64.b64encode(cipher) 
示例30
def AES_128_CBC_b64_wrapper(data, key, iv):
    obj = AES.new(compact_bytes(key, 'utf-8'), AES.MODE_CBC, compact_bytes(iv, 'utf-8'))
    input_data = pksc7_padding(data)
    out = obj.encrypt(compact_bytes(input_data, 'utf-8'))
    return base64.b64encode(out).decode('utf8')