k98kurz icon

selfhash.py

k98kurz | PRO | 06/03/22 08:07:59 PM UTC (Edited) | 0 ⭐ | 463 👁️ | Never ⏰ | []
Python |

3.34 KB

|

None

|

0 👍

/

0 👎

#!/bin/python
from hashlib import sha256
from sys import argv
 
 
FILE_HASH = '23a11c611ff4f4e04dd5ccd17fc297ad6b38dd9a295a212d2bdee0ba53cb8b27'
 
 
def initial_hash(filename: str) -> str:
    """Calculates the initial hash of this file."""
    with open(filename, 'rb') as f:
        return sha256(f.read()).digest().hex()
 
 
def final_hash(filename: str) -> str:
    """Calculates the hash of this file without the FILE_HASH line."""
    with open(filename, 'rb') as f:
        # parse file into lines
        contents = f.read()
        lines = contents.split(b'\n')
        line_index = ''
 
        # find the FILE_HASH line
        for i, l in enumerate(lines):
            if l[:9] == b'FILE_HASH':
                line_index = i
                break
 
        # remove the FILE_HASH line
        lines.remove(lines[line_index])
        contents = b'\n'.join(lines)
 
        # hash resulting contents
        return sha256(contents).digest().hex()
 
 
def persist_hash(filename: str) -> None:
    """Overwrite the FILE_HASH line with the result of final_hash."""
    # calculate correct hash
    digest = final_hash(filename)
 
    # open file
    with open(filename, 'rb') as f:
        # parse file
        contents = f.read()
        lines = contents.split(b'\n')
        line_index = ''
 
        # find correct line to replace
        for i, l in enumerate(lines):
            if l[:9] == b'FILE_HASH':
                line_index = i
                break
 
        # replace line
        lines[line_index] = b'FILE_HASH = \'' + bytes(digest, 'utf-8') + b'\''
        contents = b'\n'.join(lines)
 
        # write contents
        with open(filename, 'wb') as f2:
            f2.write(contents)
 
 
def verify_hash(filename: str) -> bool:
    """Verify that the hash specified in the FILE_HASH is valid."""
    digest = final_hash(filename)
    return digest == FILE_HASH
 
 
def license():
    """Copyleft (c) 2022 k98kurz
 
        Permission to use, copy, modify, and/or distribute this software
        for any purpose with or without fee is hereby granted, provided
        that the above copyleft notice and this permission notice appear in
        all copies.
 
        THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
        WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
        WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
        AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
        CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
        OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
        NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    """
    return license.__doc__
 
 
def main(args: list):
    filename = args[0]
    mode = args[1] if len(args) > 1 else 'help'
 
    if mode == 'help':
        print(f'usage: python {filename} [print|persist|verify]')
    elif mode == 'print':
        print(f'initial hash: {initial_hash(filename)}')
        print(f'final hash: {final_hash(filename)}')
    elif mode == 'persist':
        persist_hash(filename)
    elif mode == 'verify':
        if verify_hash(filename):
            print('verified')
        else:
            print('invalidated')
 
 
if __name__ == '__main__':
    main(argv)
 

Comments