Python Crypto.Cipher.AES 模块,MODE_CBC 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Crypto.Cipher.AES.MODE_CBC

项目:Cypher    作者:NullArray    | 项目源码 | 文件源码
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)
项目:crypt_    作者:mrx6s0    | 项目源码 | 文件源码
def encrypt(key, filename):
        chunksize = 64 * 1024
        outFile = os.path.join(os.path.dirname(filename), ".hell"+os.path.basename(filename))
        filesize = str(os.path.getsize(filename)).zfill(16)
        IV = ''

        for i in range(16):
                IV += chr(random.randint(0, 0xFF))

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

        with open(filename, "rb") as infile:
                with open(outFile, "wb") as outfile:
                        outfile.write(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))
项目:asterix    作者:suma12    | 项目源码 | 文件源码
def encrypt(self, data):
        """Encrypt sensitive data by KIK.
For (3)DES, data must be padded to BS.
For AES, if data not BS-alligned, they are padded by '80..00'"""
        l = len(data)
        if self.zAES:
            l %= 16
            if l > 0:
                data += '\x80' + '\0'*(15-l)
            key = AES.new(self.keyValue, AES.MODE_CBC, IV='\0'*16)
        else:
            # suppose 8B aligned data
            assert l % 8 == 0
            # for (3)DES KIK, ECB is used
            # KeyType.DES_IMPLICIT is supposed to be 3DES ECB
            if self.keyType in (KeyType.TDES_CBC, KeyType.DES_IMPLICIT):
                key = DES3.new(self.keyValue, DES.MODE_ECB)
            elif self.keyType in (KeyType.DES_ECB, KeyType.DES_CBC):
                key = DES.new(self.keyValue, DES.MODE_ECB)
            else:
                raise ValueError("Unknown key type %02X" % self.keyType)
        return key.encrypt(data)
项目:Cypher    作者:NullArray    | 项目源码 | 文件源码
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))
项目:matasano    作者:shainer    | 项目源码 | 文件源码
def __init__(self):
        self.iv = Random.new().read(AES.block_size)
        self.key = Random.new().read(AES.block_size)
        self.cipher = AES.new(key=self.key, mode=AES.MODE_CBC, IV=self.iv)

        texts = []
        self.plaintexts = []

        # Reads all the lines from the data, as binary strings, then decodes
        # them from base64 and applies Pkcs7 padding.
        with open('data/7.txt', 'rb') as dataFile:
            texts = dataFile.readlines()

        for text in texts:
            strText = base64.b64decode(text)
            self.plaintexts.append(Pkcs7(strText))
项目:matasano    作者:shainer    | 项目源码 | 文件源码
def CBCMacWithStates(message, iv):
    """Computes the CBC-MAC of a message given the IV.

    Returns a tuple with the hash and a list of tuples; the first
    element is the block index and the second is the intermediate state
    associated with that block, as a byte string.

    It is expected that this returns the same hash as CBC-MAC above
    given the same inputs.
    """
    M_states = []

    paddedMessage = padPKCS7(message)
    intermediateMessage = b''
    currentState = iv

    for bIndex in range(GetNumBlocks(paddedMessage)):
        intermediateMessage = GetBlock(paddedMessage, bIndex)

        cipher = AES.new(b'YELLOW SUBMARINE', AES.MODE_CBC, currentState)
        currentState = cipher.encrypt(intermediateMessage)
        currentState = currentState[-AES.block_size:]
        M_states.append( ( bIndex, currentState ) )

    return currentState, M_states
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def decrypt_aes(secret, key):
    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
项目:py-http-test-framework    作者:iyaozhen    | 项目源码 | 文件源码
def test_encrypter(self):
        """
        test_encrypter
        :return:
        """
        key = '0123456701234567'
        iv = Random.new().read(AES.block_size)
        s = '?? 10:00 AM'
        # ECB
        encrypter = tools.Encrypter(key)
        self.assertEqual(encrypter.decrypt(encrypter.encrypt(s)), s)
        # CBC
        encrypter = tools.Encrypter(key, AES.MODE_CBC, iv)
        self.assertEqual(encrypter.decrypt(encrypter.encrypt(s)), s)
        # CFB
        encrypter = tools.Encrypter(key, AES.MODE_CFB, iv)
        self.assertEqual(encrypter.decrypt(encrypter.encrypt(s)), s)
项目:steem-python    作者:steemit    | 项目源码 | 文件源码
def init_aes(shared_secret, nonce):
    """ Initialize AES instance

        :param hex shared_secret: Shared Secret to use as encryption key
        :param int nonce: Random nonce
        :return: AES instance and checksum of the encryption key
        :rtype: length 2 tuple

    """
    " Seed "
    ss = unhexlify(shared_secret)
    n = struct.pack("<Q", int(nonce))
    encryption_key = hashlib.sha512(n + ss).hexdigest()
    " Check'sum' "
    check = hashlib.sha256(unhexlify(encryption_key)).digest()
    check = struct.unpack_from("<I", check[:4])[0]
    " AES "
    key = unhexlify(encryption_key[0:64])
    iv = unhexlify(encryption_key[64:96])
    return AES.new(key, AES.MODE_CBC, iv), check
项目:public_drown_scanner    作者:nimia    | 项目源码 | 文件源码
def ciphersuite_factory(cipher_id, key, iv):
    kex, enc, mac = describe_ciphersuite(cipher_id)
    #print kex,enc,mac

    if not "AES" in enc:
        raise Exception("Encryption Cipher not supported: %s"%enc)



    if "CBC" in enc:
        mode = AES.MODE_CBC
    else:
        raise Exception("Crypto Mode not supported: %s"%enc)

    encryptor = AES.new(key, mode=mode, IV=iv)
    return PKCS7Wrapper(encryptor)
项目:sdos-core    作者:sdos    | 项目源码 | 文件源码
def decryptBytesIO(self, ciphertext):
        assert (self.key)
        ciphertext.seek(0)

        if not (ciphertext.read(len(self.outerHeader)) == self.outerHeader):
            raise TypeError('outer data header mismatch - possibly corrupt ciphertext')

        iv = ciphertext.read(self.blockSize)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        plaintext = io.BytesIO(cipher.decrypt(ciphertext.read()))
        ciphertext.close()

        if not (plaintext.read(len(self.innerHeader)) == self.innerHeader):
            raise TypeError('inner data header mismatch - possibly wrong decryption key: {}...'.format(self.key[:5]))

        plaintextNoHeader = io.BytesIO(plaintext.getvalue()[len(self.innerHeader):])
        plaintext.close()
        _unpadBytesIO(plaintextNoHeader)

        return plaintextNoHeader
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def decrypt_aes(secret, key):
    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
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def downstream_recv(self, data):
        try:
            enc=data.peek()
            if self.aes_key is None: #receive aes key
                if len(enc) < self.rsa_key_size/8:
                    return
                cmsg=enc[:self.rsa_key_size/8]
                try:
                    self.aes_key=rsa.decrypt(cmsg, self.pk)
                except rsa.pkcs1.DecryptionError:
                    self.close()
                    return
                data.drain(self.rsa_key_size/8)

                if AES is not None:
                    self.enc_cipher = AES.new(self.aes_key, AES.MODE_CBC, self._iv_enc)
                else:
                    self.enc_cipher = pyaes.AESModeOfOperationCBC(self.aes_key, iv = self._iv_enc)
            super(RSA_AESServer, self).downstream_recv(data)
        except Exception as e:
            logging.debug(e)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(AESTransport, self).__init__(*args, **kwargs)
        if "password" in kwargs:
            self.password=kwargs["password"]
        if self.password is None:
            raise TransportError("A password needs to be supplied for AES")
        self._salt = "__PupY_PBKDF2_S4l7__"
        logging.debug("deriving the key with %s iterations..."%self.iterations)
        if PBKDF2 is not None:
            self._derived_key = PBKDF2(self.password, self._salt, self.key_size, self.iterations, prf=lambda password, salt: HMAC.new(password, salt, SHA256).digest())
        else:
            self._derived_key = pbkdf2_bin(self.password, self._salt, keylen=self.key_size, iterations=self.iterations, hashfunc=hashlib.sha256)
        logging.debug("key derived ...")
        if Random:
            self._iv_enc = Random.new().read(BLOCK_SIZE)
        else:
            self._iv_enc = os.urandom(BLOCK_SIZE)
        if AES is not None:
            self.enc_cipher = AES.new(self._derived_key, AES.MODE_CBC, self._iv_enc)
        else:
            self.enc_cipher = pyaes.AESModeOfOperationCBC(self._derived_key, iv = self._iv_enc)
        self.dec_cipher = None
        self._iv_dec = None
        self.size_to_read=None
        self.first_block=b""
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def decrypt_aes(secret, key):
    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
项目:sweetshot    作者:AnCh7    | 项目源码 | 文件源码
def init_aes(shared_secret, nonce):
    """ Initialize AES instance

        :param hex shared_secret: Shared Secret to use as encryption key
        :param int nonce: Random nonce
        :return: AES instance and checksum of the encryption key
        :rtype: length 2 tuple

    """
    " Seed "
    ss = unhexlify(shared_secret)
    n = struct.pack("<Q", int(nonce))
    encryption_key = hashlib.sha512(n + ss).hexdigest()
    " Check'sum' "
    check = hashlib.sha256(unhexlify(encryption_key)).digest()
    check = struct.unpack_from("<I", check[:4])[0]
    " AES "
    key = unhexlify(encryption_key[0:64])
    iv = unhexlify(encryption_key[64:96])
    return AES.new(key, AES.MODE_CBC, iv), check
项目:Block-SSL    作者:Cr0wTom    | 项目源码 | 文件源码
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):

    #Thanks to Eli Bendersky: https://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/
    if not out_filename:
        out_filename = in_filename + '.enc'

    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))
项目:Block-SSL    作者:Cr0wTom    | 项目源码 | 文件源码
def decrypt_file(key, in_filename, out_filename=None, chunksize=24*1024):

    #Thanks to Eli Bendersky: https://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/
    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))

            outfile.truncate(origsize)
项目:Block-SSL    作者:Cr0wTom    | 项目源码 | 文件源码
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*4096):

    #Thanks to Eli Bendersky: https://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/
    if not out_filename:
        out_filename = in_filename + '.enc'

    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))
项目:Block-SSL    作者:Cr0wTom    | 项目源码 | 文件源码
def decrypt_file(key, in_filename, out_filename=None, chunksize=64*4096):

    #Thanks to Eli Bendersky: https://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/
    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))

            outfile.truncate(origsize)
项目:nc-backup-py    作者:ChinaNetCloud    | 项目源码 | 文件源码
def decrypt(self, in_file, out_file, password, key_length=32, home_folder=''):
        bs = AES.block_size
        salt = in_file.read(bs)[len('Salted__'):]
        key, iv = self.__derive_key_and_iv(password, salt, key_length, bs)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        next_chunk = ''
        finished = False
        print out_file
        # print in_file
        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])
                if padding_length < 1 or padding_length > bs:
                   raise ValueError("bad decrypt pad (%d)" % padding_length)
                # all the pad-bytes must be the same
                if chunk[-padding_length:] != (padding_length * chr(padding_length)):
                   # this is similar to the bad decrypt:evp_enc.c from openssl program
                   raise ValueError("bad decrypt")
                chunk = chunk[:-padding_length]
                finished = True
            out_file.write(chunk)
        return out_file.name
项目:PyKI    作者:pykiki    | 项目源码 | 文件源码
def decryptData(key, encdata):
    """ Decrypts a file using AES (CBC mode) with the
        given key. Parameters are similar to encrypt_file
    """

    ''' with CBC
    # converting passkey to a 32 bytes len str
    key = SHA256.new(key.encode('utf-8')).digest()
    iv = encdata[:16]
    decryptor = AES.new(key, AES.MODE_CBC, iv)
    data = decryptor.decrypt(encdata[16:])
    return(data)
    '''

    # converting passkey to a 32 bytes len str
    key = SHA256.new(key.encode('utf-8')).digest()
    iv = encdata[:16]
    cipher = AES.new(key, AES.MODE_CFB, iv)
    data = cipher.decrypt(encdata[16:])
    return(data)
项目:asterix    作者:suma12    | 项目源码 | 文件源码
def __init__(self, iKICD):
        """ Constructor for KIC/KID object.
 iKICD - coding of KIC or KID (see ETSI 102.225, 5.1.2 and 5.1.3, u8)"""
        iKICD %= 0x100
        self.iKICD = iKICD
        self.keyval = None
        if iKICD & KICD.ALGO == KICD.ALGO_DES:           # DES/3DES key
            b43 = iKICD & 0x0C           # bits 4 and 3 of KIC/KID
            self.keysize = 8 + 2*(b43 % 12)  # mapping to DES, 3DES 2k, 3DES 3k
            self.cipModule = b43 % 12 and DES3 or DES
            self.MODE = b43 == KICD.DES_ECB and DES.MODE_EBC or DES.MODE_CBC
            self.BS = 8
            self.zAES = False
        elif iKICD & 0x0F == KICD.ALGO_AES:         # AES CBC / CMAC
            self.zAES = True
            self.cipModule = AES
            self.MODE = AES.MODE_CBC
            self.BS = 16
            self.TlenB = 8     # length of CMAC, you may manually change to 4
            self.irrPoly = 0x87            # for CMAC
        else:
            raise ValueError("Only DES/AES implemented for KIC/KID")
项目:asterix    作者:suma12    | 项目源码 | 文件源码
def sign(self, data):
        """
Sign data (as str) by KID key.
Return signature as str."""
        if self.zAES:
            data = [ord(x) for x in data]
            sLB = len(data) % self.BS
            if(sLB > 0 or len(data) == 0):
                data += [0x80] + [0]*(self.BS-sLB-1)
                xorkey = self.xorKey2
            else:
                xorkey = self.xorKey1
            for i in xrange(self.BS):
                data[-self.BS+i] ^= ord(xorkey[i])
            cipher = AES.new(self.keyval, AES.MODE_CBC, IV='\0'*16)
            data = ''.join([chr(x) for x in data])
            sig = cipher.encrypt(data)[-self.BS:]
            return sig[:self.TlenB]
        else:
            padlen = len(data) % self.BS
            if padlen > 0:
                padlen = self.BS - padlen
            sig = self.cipher(data + '\0'*padlen, True)
            return sig[-self.BS:]
项目:asterix    作者:suma12    | 项目源码 | 文件源码
def wrapResp(self, resp, sw1, sw2):
        """ Wrap expected response as card would do."""
        sw = (sw1 << 8) + sw2
        if not(sw == 0x9000 or sw1 in (0x62, 0x63)):
            assert len(resp) == 0, "No response data expected"
            return [], sw1, sw2
        dresp = l2s(resp)
        if (self.SL | self.rmacSL) & SL_RENC and len(dresp) > 0:
            assert len(dresp) <= 0xEF, "Data too long for RENC+RMAC"
            k = AES.new(self.SENC, AES.MODE_ECB)
            ICV = k.encrypt(pack(">QQ", 0x8000000000000000L |
                                 self.cmdCount / 0x10000000000000000L,
                                 self.cmdCount % 0x10000000000000000L))
            k = AES.new(self.SENC, AES.MODE_CBC, IV=ICV)
            dresp = k.encrypt(pad80(dresp, 16))
        if (self.SL | self.rmacSL) & SL_RMAC:
            assert len(dresp) <= 0xF0, "Data too long for RMAC"
            data2sign = self.MACchain + dresp + chr(sw1) + chr(sw2)
            rmac = CMAC(self.SRMAC, data2sign)[:8]
            dresp += rmac
        return s2l(dresp), sw1, sw2
项目:neo-python    作者:CityOfZion    | 项目源码 | 文件源码
def ChangePassword(self, password_old, password_new):
        """
        Change the password used to protect the private key.

        Args:
            password_old (str): the current password used to encrypt the private key.
            password_new (str): the new to be used password to encrypt the private key.

        Returns:
            bool: whether the password has been changed
        """
        if not self.ValidatePassword(password_old):
            return False

        if isinstance(password_new, str):
            password_new = password_new.encode('utf-8')

        password_key = hashlib.sha256(password_new)
        self.SaveStoredData("PasswordHash", password_key)
        self.SaveStoredData("MasterKey", AES.new(self._master_key, AES.MODE_CBC, self._iv))

        return True
项目:Cryptical    作者:mathieudev    | 项目源码 | 文件源码
def aes_decrypt(blocksize, key, ciphertext):
    """Encrypt the plaintext with AES.

    This function encrypt the plaintext using AES algorithm in CBC mode.

    :parameter:
     blocksize : int
        The size of the block of the CBC mode.
     key : string
        The symmetric key used to perform AES decryption.
     ciphertext : string
        Ciphertext to decrypt.

    :return: A string, the plaintext after decryption and removing the padding.
    """

    ciphertext = base64.b64decode(ciphertext)
    iv = ciphertext[:blocksize]
    cipher = AES.new(key, AES.MODE_CBC, iv)
    paddedplaintext = cipher.decrypt(ciphertext[blocksize:])
    plaintext = unpad(paddedplaintext)

    return plaintext
项目:EasyStorj    作者:lakewik    | 项目源码 | 文件源码
def encrypt_file_aes(self, in_file, out_file, password, key_length=32):
        bs = AES.block_size
        salt = Random.new().read(bs - len('Salted__'))
        key, iv = self.derive_key_and_iv(password, salt, key_length, bs)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        out_file.write('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)
                chunk += padding_length * chr(padding_length)
                finished = True

            out_file.write(cipher.encrypt(chunk))
项目:python-muse    作者:aaroncox    | 项目源码 | 文件源码
def init_aes(shared_secret, nonce):
    """ Initialize AES instance

        :param hex shared_secret: Shared Secret to use as encryption key
        :param int nonce: Random nonce
        :return: AES instance
        :rtype: AES

    """
    " Shared Secret "
    ss = hashlib.sha512(unhexlify(shared_secret)).digest()
    " Seed "
    seed = bytes(str(nonce), 'ascii') + hexlify(ss)
    seed_digest = hexlify(hashlib.sha512(seed).digest()).decode('ascii')
    " AES "
    key = unhexlify(seed_digest[0:64])
    iv = unhexlify(seed_digest[64:96])
    return AES.new(key, AES.MODE_CBC, iv)
项目:airpyrt-tools    作者:x56    | 项目源码 | 文件源码
def decrypt_chunk(cls, encrypted_data, key, iv):
        cipher = AES.new(key, AES.MODE_CBC, iv)
        decrypted_data = ""
        bytes_left = len(encrypted_data)
        while bytes_left:
            #logging.debug("bytes left: {0:#x}".format(bytes_left))
            if bytes_left > 0x10:
                decrypted_data += cipher.decrypt(encrypted_data[-bytes_left:-(bytes_left-0x10)])
                bytes_left -= 0x10
            elif bytes_left == 0x10:
                decrypted_data += cipher.decrypt(encrypted_data[-bytes_left:])
                bytes_left = 0
            else: # bytes_left < 0x10
                #LOL: odd-sized chunk at the end is left unencrypted
                decrypted_data += encrypted_data[-bytes_left:]
                bytes_left = 0

        return decrypted_data
项目:knowledge-management    作者:dgore7    | 项目源码 | 文件源码
def encryptFile(self, filename):
        blocksize = 64 * 1024
        self.key = os.urandom(16)
        encryptedFile = filename + '.enc'

        iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
        cipher = AES.new('This is my key12', AES.MODE_CBC, iv)
        # self.key = binascii.hexlify(self.key)
        self.key = b64encode(self.key).decode('utf-8')
        fileSize = os.path.getsize(filename)

        inputFile = open(filename, 'rb')
        outputFile = open(encryptedFile, 'wb')
        outputFile.write(struct.pack('<Q', fileSize))
        outputFile.write(iv)

        while len(inputFile.read(blocksize)) > 0:
            block = inputFile.read(blocksize)
            if len(block) == 0:
                break
            if len(block) % 16 != 0:
                block += ' ' * (16 - len(block) % 16)

            outputFile.write(cipher.encrypt(block))
项目:easyATT    作者:InfiniteSamuel    | 项目源码 | 文件源码
def authenticate(self, password):
        password = password.encode('utf-8')[:127]
        hash = SHA256.new(password)
        hash.update(self.o_validation_salt)
        hash.update(self.u)
        if hash.digest() == self.o_hash:
            hash = SHA256.new(password)
            hash.update(self.o_key_salt)
            hash.update(self.u)
            return AES.new(hash.digest(), mode=AES.MODE_CBC, IV=b'\x00' * 16).decrypt(self.oe)
        hash = SHA256.new(password)
        hash.update(self.u_validation_salt)
        if hash.digest() == self.u_hash:
            hash = SHA256.new(password)
            hash.update(self.u_key_salt)
            return AES.new(hash.digest(), mode=AES.MODE_CBC, IV=b'\x00' * 16).decrypt(self.ue)
        return None
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def addcrypted2(self):
        package = self.get_post("source", "ClickAndLoad Package")
        crypted = self.get_post("crypted")
        jk = self.get_post("jk")

        crypted = standard_b64decode(unquote(crypted.replace(" ", "+")))
        jk = "%s f()" % jk
        jk = js.eval(jk)
        Key = unhexlify(jk)
        IV = Key

        obj = AES.new(Key, AES.MODE_CBC, IV)
        result = obj.decrypt(crypted).replace("\x00", "").replace("\r","").split("\n")

        result = filter(lambda x: x != "", result)

        self.add_package(package, result, 0)
项目:download-manager    作者:thispc    | 项目源码 | 文件源码
def addcrypted2(self):
        package = self.get_post("source", "ClickAndLoad Package")
        crypted = self.get_post("crypted")
        jk = self.get_post("jk")

        crypted = standard_b64decode(unquote(crypted.replace(" ", "+")))
        jk = "%s f()" % jk
        jk = js.eval(jk)
        Key = unhexlify(jk)
        IV = Key

        obj = AES.new(Key, AES.MODE_CBC, IV)
        result = obj.decrypt(crypted).replace("\x00", "").replace("\r","").split("\n")

        result = filter(lambda x: x != "", result)

        self.add_package(package, result, 0)
项目:Starfish    作者:BillWang139967    | 项目源码 | 文件源码
def encrypt(raw):
    raw = pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(KEY, AES.MODE_CBC, iv)
    return base64.b64encode( iv + cipher.encrypt(raw) )
项目:Starfish    作者:BillWang139967    | 项目源码 | 文件源码
def decrypt(enc):
    enc = base64.b64decode(enc)
    iv = enc[:16]
    cipher = AES.new(KEY, AES.MODE_CBC, iv )
    return unpad(cipher.decrypt(enc[16:]))
项目:Starfish    作者:BillWang139967    | 项目源码 | 文件源码
def encrypt(raw):
    raw = pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(KEY, AES.MODE_CBC, iv)
    return base64.b64encode( iv + cipher.encrypt(raw) )
项目:Starfish    作者:BillWang139967    | 项目源码 | 文件源码
def decrypt(enc):
    enc = base64.b64decode(enc)
    iv = enc[:16]
    cipher = AES.new(KEY, AES.MODE_CBC, iv )
    return unpad(cipher.decrypt(enc[16:]))
项目:IotCenter    作者:panjanek    | 项目源码 | 文件源码
def encrypt(plain, key, iv):
    #padding
    padnum = 16 - (len(plain) % 16)
    padded = plain + chr(padnum)*padnum

    #encrypting
    crypto = AES.new(key, AES.MODE_CBC, iv)
    encryptedBytes = crypto.encrypt(padded)      
    return encryptedBytes
项目:IotCenter    作者:panjanek    | 项目源码 | 文件源码
def decrypt(data, key, iv):
     #decrypting
     crypto = AES.new(key, AES.MODE_CBC, iv)
     decryptedBytes = crypto.decrypt(data)  

     #unpadding
     decryptedBytes = decryptedBytes[:-ord(decryptedBytes[-1])]
     return decryptedBytes
项目:enpass-cli    作者:HazCod    | 项目源码 | 文件源码
def decrypt(self, enc, key, iv ):
        # PKCS5
        cipher = AES.new(key, AES.MODE_CBC, iv )
        return self.unpad(str(cipher.decrypt(enc), 'utf-8'))
项目:data_pipeline    作者:Yelp    | 项目源码 | 文件源码
def encrypt_payload(self, payload):
        """Encrypt payload with key on machine, using AES."""
        encrypter = AES.new(
            self.key,
            AES.MODE_CBC,
            self.encryption_meta.payload
        )
        payload = self._pad_payload(payload)
        return encrypter.encrypt(payload)
项目:data_pipeline    作者:Yelp    | 项目源码 | 文件源码
def decrypt_payload(self, payload):
        decrypter = AES.new(
            self.key,
            AES.MODE_CBC,
            self.encryption_meta.payload
        )
        data = decrypter.decrypt(payload)
        return self._unpad(data)
项目:browsercookie-windows-support    作者:DavidMetcalfe    | 项目源码 | 文件源码
def _decrypt(self, value, encrypted_value, key):
        """Decrypt encoded cookies
        """
        if (sys.platform == 'darwin') or sys.platform.startswith('linux'):
            if value or (encrypted_value[:3] != b'v10'):
                return value

            # Encrypted cookies should be prefixed with 'v10' according to the
            # Chromium code. Strip it off.
            encrypted_value = encrypted_value[3:]

            # Strip padding by taking off number indicated by padding
            # eg if last is '\x0e' then ord('\x0e') == 14, so take off 14.
            def clean(x):
                last = x[-1]
                if isinstance(last, int):
                    return x[:-last].decode('utf8')
                else:
                    return x[:-ord(last)].decode('utf8')

            iv = b' ' * 16
            cipher = AES.new(key, AES.MODE_CBC, IV=iv)
            decrypted = cipher.decrypt(encrypted_value)
            return clean(decrypted)
        else:
            #Must be win32 (on win32, all chrome cookies are encrypted)
            try:
                import win32crypt
            except ImportError:
                raise BrowserCookieError('win32crypt must be available to decrypt Chrome cookie on Windows')
            return win32crypt.CryptUnprotectData(encrypted_value, None, None, None, 0)[1].decode("utf-8")
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def encrypt(self, data):
        """encrypt data with AES-CBC and sign it with HMAC-SHA256"""
        aes_key, hmac_key = self.keys
        pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
        data = data + pad * chr(pad)
        iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
        cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
        data = iv_bytes + cypher.encrypt(data)
        sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
        return data + sig
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def decrypt(self, data):
        """verify HMAC-SHA256 signature and decrypt data with AES-CBC"""
        aes_key, hmac_key = self.keys
        sig = data[-self.SIG_SIZE:]
        data = data[:-self.SIG_SIZE]
        if hmac.new(hmac_key, data, hashlib.sha256).digest() != sig:
            raise AuthenticationError("message authentication failed")
        iv_bytes = data[:self.AES_BLOCK_SIZE]
        data = data[self.AES_BLOCK_SIZE:]
        cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
        data = cypher.decrypt(data)
        return data[:-ord(data[-1])]
项目:Ushio    作者:Hanaasagi    | 项目源码 | 文件源码
def __init__(self, key):
        # ????key ?????16?AES-128??24?AES-192???32?AES-256?Bytes ??.
        if len(key) < 16:
            key = key + (16 - len(key)) * '\0'
        self.key = key[:16]
        self.mode = AES.MODE_CBC

    # ???????text??16????????text???16???????????16???
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
def encrypt(self, raw):
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return iv + cipher.encrypt(self._pad(raw))
项目:watermark    作者:lishuaijuly    | 项目源码 | 文件源码
def decrypt(self, enc):
        iv = enc[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:]))
项目:SecureSnaps    作者:NITDgpOS    | 项目源码 | 文件源码
def decrypt(ciphername,password):


    cipher = open(ciphername,'r')
    ciphertext = cipher.read()

    obj2 = AES.new(password, AES.MODE_CBC, 'This is an IV456')
    decrypted = obj2.decrypt(ciphertext)
    decrypted = decrypted.replace("n","") 

    newwidth = decrypted.split("w")[1]
    newheight = decrypted.split("h")[1]

     heightr = "h" + str(newheight) + "h"