Search code examples
dropboxdropbox-api

Locally calculate dropbox hash of files


Dropbox rest api, in function metatada has a parameter named "hash" https://www.dropbox.com/developers/reference/api#metadata

Can I calculate this hash locally without call any remote api rest function?

I need know this value to reduce upload bandwidth.


Solution

  • https://www.dropbox.com/developers/reference/content-hash explains how Dropbox computes their file hashes. A Python implementation of this is below:

    import hashlib
    import math
    import os
    
    DROPBOX_HASH_CHUNK_SIZE = 4*1024*1024
    
    def compute_dropbox_hash(filename):
        file_size = os.stat(filename).st_size
        with open(filename, 'rb') as f:
            block_hashes = b''
            while True:
                chunk = f.read(DROPBOX_HASH_CHUNK_SIZE)
                if not chunk:
                    break
                block_hashes += hashlib.sha256(chunk).digest()
            return hashlib.sha256(block_hashes).hexdigest()