lbry-sdk/lbry/crypto/hash.py

48 lines
1.1 KiB
Python
Raw Normal View History

import hashlib
import hmac
from binascii import hexlify, unhexlify
def sha256(x):
""" Simple wrapper of hashlib sha256. """
return hashlib.sha256(x).digest()
def sha512(x):
""" Simple wrapper of hashlib sha512. """
return hashlib.sha512(x).digest()
def ripemd160(x):
""" Simple wrapper of hashlib ripemd160. """
h = hashlib.new('ripemd160')
h.update(x)
return h.digest()
def double_sha256(x):
""" SHA-256 of SHA-256, as used extensively in bitcoin. """
return sha256(sha256(x))
def hmac_sha512(key, msg):
""" Use SHA-512 to provide an HMAC. """
return hmac.new(key, msg, hashlib.sha512).digest()
def hash160(x):
""" RIPEMD-160 of SHA-256.
Used to make bitcoin addresses from pubkeys. """
return ripemd160(sha256(x))
2020-10-13 20:34:19 +02:00
def hash_to_hex_str(x: bytes) -> str:
""" Convert a big-endian binary hash to displayed hex string.
Display form of a binary hash is reversed and converted to hex. """
2020-10-13 20:34:19 +02:00
return hexlify(x[::-1])
2020-10-13 20:34:19 +02:00
def hex_str_to_hash(x: str) -> bytes:
""" Convert a displayed hex string to a binary hash. """
2020-10-13 20:34:19 +02:00
return unhexlify(x)[::-1]