/ client_code / hashlib.py
hashlib.py
1 # SPDX-License-Identifier: MIT 2 # 3 # Copyright (c) 2021 The Anvil Extras project team members listed at 4 # https://github.com/anvilistas/anvil-extras/graphs/contributors 5 # 6 # This software is published at https://github.com/anvilistas/anvil-extras 7 8 from functools import partial 9 10 from anvil.js import window 11 12 __version__ = "3.1.0" 13 14 15 def digest(algorithm, data): 16 """Returns the digest of the data using the specified algorithm. 17 18 Parameters 19 ---------- 20 algorithm : str 21 The algorithm to use. 22 data : str or bytes 23 The data to digest. 24 """ 25 if not isinstance(data, (bytes, str)): 26 raise TypeError("data must be a string or bytes object") 27 28 if isinstance(data, str): 29 data = data.encode("utf-8") 30 31 hash_buffer = window.crypto.subtle.digest(algorithm, data) 32 hash_array = window.Uint8Array(hash_buffer) 33 return hash_array.hex() 34 35 36 sha1 = partial(digest, "SHA-1") 37 sha256 = partial(digest, "SHA-256") 38 sha384 = partial(digest, "SHA-384") 39 sha512 = partial(digest, "SHA-512") 40 41 if __name__ == "__main__": 42 _ = "Hello world!" 43 sha1(_) 44 sha256(_) 45 sha384(_) 46 sha512(_)