hashtools.py 862 Bytes
Newer Older
1
2
3
"""hash functions for the cubicbweb-file cube

:organization: Logilab
4
:copyright: 2018-2022 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
"""

import re
import hashlib


def compute_hash(value, alg):
    hashvalue = compute_row_hash(value, alg)
    if hashvalue:
        return '{%s}%s' % (alg, hashvalue)


def compute_row_hash(value, alg):
    if value is not None:
        hasher = hashlib.new(alg, value)
Simon Chabot's avatar
Simon Chabot committed
21
        return str(hasher.hexdigest())
22
23
24
25
26
27
28
29
30
31
32
33


def check_hash(hash_value, value):
    m = re.match('{(?P<alg>[A-Za-z0-9]+)}(?P<hash>.+)', hash_value)
    if m:
        alg = m.group('alg')
        hashhex = m.group('hash')
    else:  # bw compat, used to be sha1
        alg = 'sha1'
        hashhex = hash_value
    comphash = compute_row_hash(value, alg=alg)
    return comphash == hashhex