crypto.py (1251B)
1 # standard imports 2 import hashlib 3 import os 4 5 6 class Salter: 7 """Base class to provide cryptographic salt for cache objects that should be obfuscated. 8 9 By default a random base value will be generated. The salt will be deterministically determined from the value and the provided chain spec. 10 11 :param chain_spec: Chain spec to generate the salt with. 12 :type chain_spec: chainlib.chain.ChainSpec 13 """ 14 salt = os.urandom(32) 15 16 def __init__(self, chain_spec): 17 self.chain_spec = chain_spec 18 self.ionized_salt = self.salt 19 self.ionized_salt = self.sprinkle(str(chain_spec).encode('utf-8')) 20 21 22 def sprinkle(self, data): 23 """Hash the given data with the salt 24 25 :param data: Input data 26 :type data: bytes 27 :rtype: bytes 28 :returns: Hashed, salted value 29 30 """ 31 h = hashlib.new('sha256') 32 if isinstance(data, list): 33 for d in data: 34 h.update(d) 35 else: 36 h.update(data) 37 h.update(self.ionized_salt) 38 return h.digest() 39 40 41 def root_key(self): 42 """Returns the salt value generated from the chain spec. 43 44 :rtype: bytes 45 :returns: Salt 46 """ 47 return self.ionized_salt