Verifies the integrity of a file uploaded to Box
501052
def verify_uploaded_file(
            self,
            destination_folder_id,
            source_path,
            verbose = True,
    ):
        '''
        
        '''
        source_file_size = os.stat(source_path).st_size

        total_part_size = 0
        file_position = 0
        uploaded_box_file_ids = self.find_file( destination_folder_id, os.path.basename( source_path ) )
        total_sha1 = hashlib.sha1()
        for i, file_id in enumerate(uploaded_box_file_ids):
            file_info = self.client.file( file_id = file_id ).get()
            uploaded_sha1 = file_info.response_object['sha1']
            uploaded_size = file_info.response_object['size']

            part_sha1 = read_sha1( source_path, start_byte = file_position, read_size = uploaded_size, extra_hashers = [total_sha1] )
            if part_sha1.hexdigest() != uploaded_sha1:
                print( '\n' )
                print( 'Part sha1: ' + part_sha1.hexdigest() )
                print( 'Uploaded sha1: ' + uploaded_sha1 )
                print('Sha1 hash of uploaded file {0} ({1}) does not match'.format(file_info.response_object['name'], file_id) )
                return False

            file_position += uploaded_size
            total_part_size += uploaded_size
            if len(uploaded_box_file_ids) > 1:
                print( 'Finished verifying part {0} of {1} of {2}'.format( i+1, len(uploaded_box_file_ids), file_id ) )

        assert( source_file_size == total_part_size )

        if verbose:
            print( 'Verified uploaded file {0} ({1}) with sha1: {2}'.format(source_path, file_id, total_sha1.hexdigest()) )

        return True
742702
function _validate_files(&$files) {
        global $CFG, $COURSE;

        $files = array();

        if (empty($_FILES)) {
            // we do not need to do any checks because no files were submitted
            // note: server side rules do not work for files - use custom verification in validate() instead
            return true;
        }

        $errors = array();
        $filenames = array();

        // now check that we really want each file
        foreach ($_FILES as $elname=>$file) {
            $required = $this->_form->isElementRequired($elname);

            if ($file['error'] == 4 and $file['size'] == 0) {
                if ($required) {
                    $errors[$elname] = get_string('required');
                }
                unset($_FILES[$elname]);
                continue;
            }

            if (!empty($file['error'])) {
                $errors[$elname] = file_get_upload_error($file['error']);
                unset($_FILES[$elname]);
                continue;
            }

            if (!is_uploaded_file($file['tmp_name'])) {
                // TODO: improve error message
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }

            if (!$this->_form->elementExists($elname) or !$this->_form->getElementType($elname)=='file') {
                // hmm, this file was not requested
                unset($_FILES[$elname]);
                continue;
            }

            // NOTE: the viruses are scanned in file picker, no need to deal with them here.

            $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
            if ($filename === '') {
                // TODO: improve error message - wrong chars
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }
            if (in_array($filename, $filenames)) {
                // TODO: improve error message - duplicate name
                $errors[$elname] = get_string('error');
                unset($_FILES[$elname]);
                continue;
            }
            $filenames[] = $filename;
            $_FILES[$elname]['name'] = $filename;

            $files[$elname] = $_FILES[$elname]['tmp_name'];
        }

        // return errors if found
        if (count($errors) == 0){
            return true;

        } else {
            $files = array();
            return $errors;
        }
    }
239474
def verifyChainFromCAFile(self, cafile, untrusted_file=None):
        
        try:
            f = open(cafile, "rb")
            ca_certs = f.read()
            f.close()
        except Exception:
            raise Exception("Could not read from cafile")

        anchors = [Cert(c) for c in split_pem(ca_certs)]

        untrusted = None
        if untrusted_file:
            try:
                f = open(untrusted_file, "rb")
                untrusted_certs = f.read()
                f.close()
            except Exception:
                raise Exception("Could not read from untrusted_file")
            untrusted = [Cert(c) for c in split_pem(untrusted_certs)]

        return self.verifyChain(anchors, untrusted)
939758
private void verifyChunkedSums(
      byte[] data, int dataOff, int dataLen,
      byte[] checksums, int checksumsOff, String fileName,
      long basePos) throws ChecksumException {
    
    int remaining = dataLen;
    int dataPos = 0;
    while (remaining > 0) {
      int n = Math.min(remaining, bytesPerChecksum);
      
      summer.reset();
      summer.update(data, dataOff + dataPos, n);
      dataPos += n;
      remaining -= n;
      
      int calculated = (int)summer.getValue();
      int stored = (checksums[checksumsOff] << 24 & 0xff000000) |
        (checksums[checksumsOff + 1] << 16 & 0xff0000) |
        (checksums[checksumsOff + 2] << 8 & 0xff00) |
        checksums[checksumsOff + 3] & 0xff;
      checksumsOff += 4;
      if (calculated != stored) {
        long errPos = basePos + dataPos - n;
        throw new ChecksumException(
            "Checksum error: "+ fileName + " at "+ errPos +
            " exp: " + stored + " got: " + calculated, errPos);
      }
    }
  }
885856
def validate(self):
        
        # Ange Albertini (@angie4771) can kill me for this! :)
        if self.dosHeader.e_magic.value != consts.MZ_SIGNATURE:
            raise excep.PEException("Invalid MZ signature. Found %d instead of %d." % (self.dosHeader.magic.value, consts.MZ_SIGNATURE))
        
        if self.dosHeader.e_lfanew.value > len(self):
            raise excep.PEException("Invalid e_lfanew value. Probably not a PE file.")
            
        if self.ntHeaders.signature.value != consts.PE_SIGNATURE: 
            raise excep.PEException("Invalid PE signature. Found %d instead of %d." % (self.ntHeaders.optionaHeader.signature.value, consts.PE_SIGNATURE))
            
        if self.ntHeaders.optionalHeader.numberOfRvaAndSizes.value > 0x10:
            print excep.PEWarning("Suspicious value for NumberOfRvaAndSizes: %d." % self.ntHeaders.optionaHeader.numberOfRvaAndSizes.value)
644215
def file_verified?(path, expected_digest, digest_type=:md5)
      return false unless file_exists?(path)
      raise "Unknown disgest type: #{digest_type}" unless can?("digest_#{digest_type}")
      digest = self.send("digest_#{digest_type}", path).first
      info "#{digest_type} (#{path}) = #{digest}"
      digest.to_s == expected_digest.to_s
    end
1216063
def isValid( self ):
        
        check = nativestring(self._filepathEdit.text()).split(os.path.pathsep)[0]
        if ( self.filepathMode() == XFilepathEdit.Mode.SaveFile ):
            check = os.path.dirname(check)
        
        return os.path.exists(check)
34573
public function isValid()
    {
        $value = $this->field->getValue();

        // no file uploaded?
        if (!$value || !isset($value['error']) || $value['error'] == UPLOAD_ERR_NO_FILE) {
            $this->setErrorMessage($this->messages['required']);
            // required ?
            return !$this->required;
        }

        // check the uploaded file
        switch ($value['error']) {
            case UPLOAD_ERR_OK:
                break;

            case UPLOAD_ERR_FORM_SIZE:
            case UPLOAD_ERR_INI_SIZE:
                $this->setErrorMessage($this->messages['file_too_big']);
                return false;

            case UPLOAD_ERR_PARTIAL:
                $this->setErrorMessage($this->messages['incomplete']);
                return false;

            case UPLOAD_ERR_NO_TMP_DIR:
            case UPLOAD_ERR_CANT_WRITE:
                $this->setErrorMessage($this->messages['cannot_write']);
                return false;

            case UPLOAD_ERR_EXTENSION:
            default:
                $this->setErrorMessage($this->messages['error']);
                return false;
        }

        /**
         * if here, the file was uploaded.
         * Validate the uploaded file against our settings (blacklist, whitelist, etc)
         */

        // retrieve the extension
        if (!$this->isExtensionAllowed($value['name'])) {
            $this->setErrorMessage(sprintf($this->messages['wrong_extension'], implode(',', $this->allowedExtensions)));
            return false;
        }

        if (!$this->isMimetypeAllowed($value['tmp_name'], $value['type'])) {
            $this->setErrorMessage($this->messages['wrong_type']);
            return false;
        }

        $size = filesize($value['tmp_name']);

        // validate the upload file size
        if ($this->maxFilesize && $size > $this->maxFilesize) {
            $this->setErrorMessage(sprintf($this->messages['file_larger_then'], $this->maxFilesize / 1024));
            return false;
        }
        if ($this->minFilesize && $size < $this->minFilesize) {
            $this->setErrorMessage(sprintf($this->messages['file_smaller_then'], $this->minFilesize / 1024));
            return false;
        }

        // if here, the extension and the mime type are validated! The file is good!
        return true;
    }
1147517
def upload_verify(self, file_location, dataset=None):
        """"""

        path = '/api/1.0/upload/verify'
        query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location)
        if dataset:
            query = 'doNotGenerateAdvanceReport=true&filePath={}&datasetId={}'.format(file_location, dataset)

        return self._api_get(definition.UploadVerifyResponse, path, query)
871832
def verify(self, sign, *args, **kwargs):
        '''
        
        '''
        return self.verify_file(self.create_stream(sign), *args, **kwargs)
973052
def valid_file?(entry)
      ext = File.extname(entry).gsub(/\./, "").downcase
      File.file?(source.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES
    end
1254296
function validateDV(value, options) {
	var steps = options.algorithmSteps;

	// Step 01: Handle String
	var handledStr = algorithmSteps.handleStr[steps[0]](value);

	// Step 02: Sum chars
	var sum = algorithmSteps.sum[steps[1]](handledStr, options.pesos);

	// Step 03: Rest calculation
	var rest = algorithmSteps.rest[steps[2]](sum);

	// Fixed Step: Get current DV
	var currentDV = parseInt(handledStr[options.dvpos]);

	// Step 04: Expected DV calculation
	var expectedDV = algorithmSteps.expectedDV[steps[3]](rest, handledStr);

	// Fixed step: DV verification
	return currentDV === expectedDV;
}
530083
def verify_image(file:Path, idx:int, delete:bool, max_size:Union[int,Tuple[int,int]]=None, dest:Path=None, n_channels:int=3,
                 interp=PIL.Image.BILINEAR, ext:str=None, img_format:str=None, resume:bool=False, **kwargs):
    ""
    try:
        # deal with partially broken images as indicated by PIL warnings
        with warnings.catch_warnings():
            warnings.filterwarnings('error')
            try:
                with open(file, 'rb') as img_file: PIL.Image.open(img_file)
            except Warning as w:
                if "Possibly corrupt EXIF data" in str(w):
                    if delete: # green light to modify files
                        print(f"{file}: Removing corrupt EXIF data")
                        warnings.simplefilter("ignore")
                        # save EXIF-cleaned up image, which happens automatically
                        PIL.Image.open(file).save(file)
                    else: # keep user's files intact
                        print(f"{file}: Not removing corrupt EXIF data, pass `delete=True` to do that")
                else: warnings.warn(w)

        img = PIL.Image.open(file)
        imgarr = np.array(img)
        img_channels = 1 if len(imgarr.shape) == 2 else imgarr.shape[2]
        if (max_size is not None and (img.height > max_size or img.width > max_size)) or img_channels != n_channels:
            assert isinstance(dest, Path), "You should provide `dest` Path to save resized image"
            dest_fname = dest/file.name
            if ext is not None: dest_fname=dest_fname.with_suffix(ext)
            if resume and os.path.isfile(dest_fname): return
            if max_size is not None:
                new_sz = resize_to(img, max_size)
                img = img.resize(new_sz, resample=interp)
            if n_channels == 3: img = img.convert("RGB")
            img.save(dest_fname, img_format, **kwargs)
    except Exception as e:
        print(f'{e}')
        if delete: file.unlink()
1325958
def validate(self, data, offset):
        """"""
        recorded_checksum = self.field.getval()

        # convert negative offset to positive
        if offset < 0:
            offset += len(data)

        # replace checksum region with zero
        data = b''.join((data[:offset],
                         b"\x00" * self.bytes_required,
                         data[offset + self.bytes_required:]))
        actual_checksum = self.algo(data[self.start:self.end])
        if recorded_checksum != actual_checksum:
            raise SuitcaseChecksumException(
                "recorded checksum %r did not match actual %r.  full data: %r",
                recorded_checksum, actual_checksum, data)
869475
def _validate_signature_compatibility(self, boxes):
        """"""
        # Check for a bad sequence of boxes.
        # 1st two boxes must be 'jP  ' and 'ftyp'
        if boxes[0].box_id != 'jP  ' or boxes[1].box_id != 'ftyp':
            msg = ("The first box must be the signature box and the second "
                   "must be the file type box.")
            raise IOError(msg)

        # The compatibility list must contain at a minimum 'jp2 '.
        if 'jp2 ' not in boxes[1].compatibility_list:
            msg = "The ftyp box must contain 'jp2 ' in the compatibility list."
            raise IOError(msg)
1243908
public function isValid()
    {
        $isOk = $this->error === UPLOAD_ERR_OK;

        return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
    }
239515
def is_valid_image(self, raw_data):
        
        with NamedTemporaryFile(mode='wb') as fp:
            fp.write(raw_data)
            fp.flush()
            args = settings.THUMBNAIL_IDENTIFY.split(' ')
            args.append(fp.name + '[0]')
            p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            retcode = p.wait()
        return retcode == 0