Aligns the encrypted file with the decrypted data offset.

    Args:
      decrypted_data_offset (int): decrypted data offset.
341617
def _AlignDecryptedDataOffset(self, decrypted_data_offset):
    
    self._file_object.seek(0, os.SEEK_SET)

    self._decrypter = self._GetDecrypter()
    self._decrypted_data = b''

    encrypted_data_offset = 0
    encrypted_data_size = self._file_object.get_size()

    while encrypted_data_offset < encrypted_data_size:
      read_count = self._ReadEncryptedData(self._ENCRYPTED_DATA_BUFFER_SIZE)
      if read_count == 0:
        break

      encrypted_data_offset += read_count

      if decrypted_data_offset < self._decrypted_data_size:
        self._decrypted_data_offset = decrypted_data_offset
        break

      decrypted_data_offset -= self._decrypted_data_size
1314878
def decrypt(data)
      raise NoPrivateKeyError, "Private key file: #{private_key_file}" unless private?
      
      decrypted_data = data.unpack('m')[0]
      private_rsa.private_decrypt(decrypted_data)
    end
1154536
def aes_cbc_decrypt_data(symkey, iv, encdata, unpad):
    # type: (bytes, bytes, bytes, bool) -> bytes
    
    cipher = cryptography.hazmat.primitives.ciphers.Cipher(
        cryptography.hazmat.primitives.ciphers.algorithms.AES(symkey),
        cryptography.hazmat.primitives.ciphers.modes.CBC(iv),
        backend=cryptography.hazmat.backends.default_backend()).decryptor()
    decrypted = cipher.update(encdata) + cipher.finalize()
    if unpad:
        return pkcs7_unpad(decrypted)
    else:
        return decrypted
47532
def read_data(self, offsets):
        # type: (Descriptor, Offsets) -> Tuple[bytes, Offsets]
        
        newoffset = None
        if not self.local_path.use_stdin:
            if offsets.num_bytes == 0:
                return None, None
            # compute start from view
            start = self.local_path.view.fd_start + offsets.range_start
            # encrypted offsets will read past the end of the file due
            # to padding, but will be accounted for after encryption+padding
            with self.local_path.absolute_path.open('rb') as fd:
                fd.seek(start, 0)
                data = fd.read(offsets.num_bytes)
        else:
            data = blobxfer.STDIN.read(self._chunk_size)
            if not data:
                with self._meta_lock:
                    self._offset -= offsets.num_bytes
                    self._ase.size -= offsets.num_bytes
                    self._total_chunks -= 1
                    self._chunk_num -= 1
                    self._outstanding_ops -= 1
            else:
                num_bytes = len(data)
                with self._meta_lock:
                    self._offset -= offsets.num_bytes
                    self._ase.size -= offsets.num_bytes
                    newoffset = Offsets(
                        chunk_num=self._chunk_num - 1,
                        num_bytes=num_bytes,
                        range_start=self._offset,
                        range_end=self._offset + num_bytes - 1,
                        pad=False,
                    )
                    self._total_chunks += 1
                    self._outstanding_ops += 1
                    self._offset += num_bytes
                    self._ase.size += num_bytes
        if self.must_compute_md5 and data:
            with self._hasher_lock:
                self.md5.update(data)
                if self.is_resumable:
                    self._md5_cache[self._chunk_num - 1] = self.md5.hexdigest()
        return data, newoffset
359734
def encrypt(self, data):
        '''
        
        '''
        aes_key, hmac_key = self.keys
        pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE
        if six.PY2:
            data = data + pad * chr(pad)
        else:
            data = data + salt.utils.stringutils.to_bytes(pad * chr(pad))
        iv_bytes = os.urandom(self.AES_BLOCK_SIZE)
        if HAS_M2:
            cypher = EVP.Cipher(alg='aes_192_cbc', key=aes_key, iv=iv_bytes, op=1, padding=False)
            encr = cypher.update(data)
            encr += cypher.final()
        else:
            cypher = AES.new(aes_key, AES.MODE_CBC, iv_bytes)
            encr = cypher.encrypt(data)
        data = iv_bytes + encr
        sig = hmac.new(hmac_key, data, hashlib.sha256).digest()
        return data + sig
213759
def decrypt_filedata(data, keys):
    ''''''
    # The last 16 bytes / 128 bits of data is the GCM tag
    # https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :-
    # 7. Let ciphertext be equal to C | T, where '|' denotes concatenation.
    data.seek(-16, 2)
    tag = data.read()

    # now truncate the file to only contain encrypted data
    data.seek(-16, 2)
    data.truncate()
    data.seek(0)

    plain = tempfile.NamedTemporaryFile(mode='w+b', delete=False)

    pbar = progbar(fileSize(data))

    obj = Cryptodome.Cipher.AES.new(keys.encryptKey, Cryptodome.Cipher.AES.MODE_GCM, keys.encryptIV)
    prev_chunk = b''
    for chunk in iter(lambda: data.read(CHUNK_SIZE), b''):
        plain.write(obj.decrypt(prev_chunk))
        pbar.update(len(chunk))
        prev_chunk = chunk

    plain.write(obj.decrypt_and_verify(prev_chunk, tag))
    data.close()
    pbar.close()

    plain.seek(0)
    return plain
1359317
def add_encrypted(public, encrypted_a, encrypted_b, output):
    
    log("Loading public key")
    publickeydata = json.load(public)
    pub = load_public_key(publickeydata)

    log("Loading first encrypted number")
    enc_a = load_encrypted_number(encrypted_a, pub)

    log("Loading second encrypted number")
    enc_b = load_encrypted_number(encrypted_b, pub)

    log("Adding encrypted numbers together")

    enc_result = enc_a + enc_b
    serialised_result = serialise_encrypted(enc_result)
    print(serialised_result, file=output)
947606
def offset_data(data_section, offset, readable = False, wraparound = False):
    
    for pos in range(0, len(data_section)/2):
        data_section = offset_byte_in_data(data_section, offset, pos, readable, wraparound)

    return data_section
586582
def align(offset, alignment):
    
    if offset % alignment == 0:
        return offset
    return offset + (alignment - (offset % alignment))
1303512
def write(self, str):
        ''''''

        if self.closed: raise ValueError('File closed')
        if self._mode in _allowed_read:
            raise Exception('File opened for read only')

        if self._valid is not None:
            raise Exception('file already finalized')

        if not self._done_header:
            self._write_header()

        # Encrypt and write the data
        encrypted = self._crypto.encrypt(str)
        self._checksumer.update(encrypted)
        self._fp.write(encrypted)
358216
def encrypt(data)
      Digest::const_get(algorithm.upcase).hexdigest(build(data, salt))
    end
860937
def Decrypt(self, encrypted_data):
    
    index_split = -(len(encrypted_data) % DES3.block_size)
    if index_split:
      remaining_encrypted_data = encrypted_data[index_split:]
      encrypted_data = encrypted_data[:index_split]
    else:
      remaining_encrypted_data = b''

    decrypted_data = self._des3_cipher.decrypt(encrypted_data)

    return decrypted_data, remaining_encrypted_data
445129
def parse(buffer, offset = 0)
      return 0 if buffer.nil? || (buffer == '') || (buffer.length <= MAGIC_HEADER_SIZE + 2)

      # Symmetric Encryption Header
      #
      # Consists of:
      #    4 Bytes: Magic Header Prefix: @Enc
      #    1 Byte:  The version of the cipher used to encrypt the header.
      #    1 Byte:  Flags:
      #       Bit 1: Whether the data is compressed
      #       Bit 2: Whether the IV is included
      #       Bit 3: Whether the Key is included
      #       Bit 4: Whether the Cipher Name is included
      #       Bit 5: Future use
      #       Bit 6: Future use
      #       Bit 7: Future use
      #       Bit 8: Future use
      #    2 Bytes: IV Length (little endian), if included.
      #      IV in binary form.
      #    2 Bytes: Key Length (little endian), if included.
      #      Key in binary form
      #    2 Bytes: Cipher Name Length (little endian), if included.
      #      Cipher name it UTF8 text

      buffer.force_encoding(SymmetricEncryption::BINARY_ENCODING)
      header = buffer.byteslice(offset, MAGIC_HEADER_SIZE)
      return 0 unless header == MAGIC_HEADER

      offset += MAGIC_HEADER_SIZE

      # Remove header and extract flags
      self.version = buffer.getbyte(offset)
      offset      += 1

      unless cipher
        raise(
          SymmetricEncryption::CipherError,
          "Cipher with version:#{version.inspect} not found in any of the configured SymmetricEncryption ciphers"
        )
      end

      flags   = buffer.getbyte(offset)
      offset += 1

      self.compress = (flags & FLAG_COMPRESSED) != 0

      if (flags & FLAG_IV) != 0
        self.iv, offset = read_string(buffer, offset)
      else
        self.iv = nil
      end

      if (flags & FLAG_KEY) != 0
        encrypted_key, offset = read_string(buffer, offset)
        self.key              = cipher.binary_decrypt(encrypted_key)
      else
        self.key = nil
      end

      if (flags & FLAG_CIPHER_NAME) != 0
        self.cipher_name, offset = read_string(buffer, offset)
      else
        self.cipher_name = nil
      end

      if (flags & FLAG_AUTH_TAG) != 0
        self.auth_tag, offset = read_string(buffer, offset)
      else
        self.auth_tag = nil
      end

      offset
    end
225950
def align_after(self, offset):
        
        f = self.reader
        if offset <= 0:  # FIXME what is a negative offset??
            f.seek(0)
            self._block_count = 0
            self._read_header()  # FIXME we can't extimate how big it is...
            return
        sm = self.sync_marker
        sml = len(sm)
        pos = offset
        while pos < self.file_length - sml:
            f.seek(pos)
            data = f.read(self.FORWARD_WINDOW_SIZE)
            sync_offset = data.find(sm)
            if sync_offset > -1:
                f.seek(pos + sync_offset)
                self._block_count = 0
                return
            pos += len(data)
1366746
def signed_data_match(self, data, matched_data, url_safe=True):
        
        try:
            u_data = self.unsign_data(data, url_safe=url_safe)
            return u_data == matched_data
        except Exception as e:
            return False
1118229
def _AlignUncompressedDataOffset(self, uncompressed_data_offset):
    
    if self._zip_ext_file:
      self._zip_ext_file.close()
      self._zip_ext_file = None

    try:
      # The open can fail if the file path in the local file header
      # does not use the same path segment separator as the corresponding
      # entry in the central directory.
      self._zip_ext_file = self._zip_file.open(self._zip_info, 'r')
    except zipfile.BadZipfile as exception:
      raise IOError(
          'Unable to open ZIP file with error: {0!s}'.format(exception))

    self._uncompressed_data = b''
    self._uncompressed_data_size = 0
    self._uncompressed_data_offset = 0

    while uncompressed_data_offset > 0:
      self._ReadCompressedData(self._UNCOMPRESSED_DATA_BUFFER_SIZE)

      if uncompressed_data_offset < self._uncompressed_data_size:
        self._uncompressed_data_offset = uncompressed_data_offset
        break

      uncompressed_data_offset -= self._uncompressed_data_size
311854
def Decrypt(self, encrypted_data):
    
    index_split = -(len(encrypted_data) % AES.block_size)
    if index_split:
      remaining_encrypted_data = encrypted_data[index_split:]
      encrypted_data = encrypted_data[:index_split]
    else:
      remaining_encrypted_data = b''

    decrypted_data = self._aes_cipher.decrypt(encrypted_data)

    return decrypted_data, remaining_encrypted_data