def verify_github_signature(request=None): """ Validates the github webhook signature :param request containing the header and body :type: flask.request object or None :return: None or raise """ if request is None: raise NoSignatureInfo("No request object given") sig = request.headers.get( current_app.config.get('GITHUB_SIGNATURE_HEADER')) if sig is None: raise NoSignatureInfo("No signature header found") digestmod, sig = sig.split('=') h = hmac.new( current_app.config['GITHUB_SECRET'], msg=request.data, digestmod=hashlib.__getattribute__(digestmod), ) if h.hexdigest() != sig: raise InvalidSignature("Signature not validated") return True
def verify_github_signature(request=None): """ Validates the GitHub webhook signature :param request containing the header and body :type: flask.request object or None :return: None or raise """ if request is None: raise NoSignatureInfo("No request object given") sig = request.headers.get(current_app.config.get("GITHUB_SIGNATURE_HEADER")) if sig is None: raise NoSignatureInfo("No signature header found") digestmod, sig = sig.split("=") h = hmac.new( current_app.config["GITHUB_SECRET"], msg=request.data, digestmod=hashlib.__getattribute__(digestmod) ) if h.hexdigest() != sig: raise InvalidSignature("Signature not validated") return True
def hash(s): import hashlib s = s.lower() if s.startswith('sha-'): s = 'sha' + s[4:] if s in dir(hashlib): return hashlib.__getattribute__(s) return None
def PRF(key, input_str, output_len=DEFAULT_PRF_OUTPUT_LEN, hashfunc='sha1'): """Creates pseudorandom output based on key and specified input. The hmac is used to create a prf that accepts input of varying size and outputs pseudorandom str of varying size. Args: key: used to create pseudorandom output. input_str: a str that will be interpreted as raw bytes, mapped to a pseudorandom output. output_len: the length of the output requested in bytes - default is 16, and has to be less than 100,000,000. hashfunc: the underlying hash func used - default is 'sha1'. Other hashes guaranteed to work are md5, sha224, sha256, sha384, and sha512 although more may work on a specific platform. Returns: a pseudorandom str of output_len consisting of the concatenation of 16 bytes of hmac(0, input), 16 bytes of hmac(1, input),....,. Raises: ValueError: When key or output_len is empty, or input_str is not str. """ if len(key) < 1: raise ValueError('Key to PRF has to be a byte or larger.') if output_len < 1: raise ValueError('Prf output length has to be a byte or larger.') if not isinstance(input_str, str): raise ValueError('Expected str type for input_str, but got: %s' % type(input_str)) count = 0 output = [] for _ in xrange(output_len / 16): output.append( hmac.new(key, IntToFixedSizeString(count) + input_str, hashlib.__getattribute__(hashfunc)).digest()[:16]) count += 1 # if output_len is not a multiple of 16 then add the last partial block. if output_len % 16 != 0: output.append( hmac.new(key, IntToFixedSizeString(count) + input_str, hashlib.__getattribute__(hashfunc)).digest()[:output_len % 16]) return ''.join(output)
def spoton_account_save(self, data=None): spoton_users_collection = self.__conn__['spoton']['users'] spoton_user = spoton_users_collection.find_one({'username':data["username"]}) lib = hashlib.__getattribute__("sha1") hex = lib(data['password']).hexdigest() if spoton_user: spoton_users_collection.update({'username':data["username"]},{'$set':{'password':hex}}) else: spoton_users_collection.insert({'username':data["username"],'password':hex,'hotspot_account':True})
def PRF(key, input_str, output_len=DEFAULT_PRF_OUTPUT_LEN, hashfunc='sha1'): """Creates pseudorandom output based on key and specified input. The hmac is used to create a prf that accepts input of varying size and outputs pseudorandom str of varying size. Args: key: used to create pseudorandom output. input_str: a str that will be interpreted as raw bytes, mapped to a pseudorandom output. output_len: the length of the output requested in bytes - default is 16, and has to be less than 100,000,000. hashfunc: the underlying hash func used - default is 'sha1'. Other hashes guaranteed to work are md5, sha224, sha256, sha384, and sha512 although more may work on a specific platform. Returns: a pseudorandom str of output_len consisting of the concatenation of 16 bytes of hmac(0, input), 16 bytes of hmac(1, input),....,. Raises: ValueError: When key or output_len is empty, or input_str is not str. """ if len(key) < 1: raise ValueError('Key to PRF has to be a byte or larger.') if output_len < 1: raise ValueError('Prf output length has to be a byte or larger.') if not isinstance(input_str, str): raise ValueError('Expected str type for input_str, but got: %s' % type(input_str)) count = 0 output = [] for _ in xrange(output_len / 16): output.append(hmac.new(key, IntToFixedSizeString(count) + input_str, hashlib.__getattribute__(hashfunc)).digest()[:16]) count += 1 # if output_len is not a multiple of 16 then add the last partial block. if output_len % 16 != 0: output.append(hmac.new( key, IntToFixedSizeString(count) + input_str, hashlib.__getattribute__(hashfunc)).digest()[:output_len % 16]) return ''.join(output)
def __getattr__(self, attr): attrfunc = hashlib.__getattribute__(attr) if attr not in self.algos: return attrfunc def hashfunc(stream): d = attrfunc() if type(stream) is file: attr = iter(lambda:attr.read(4096), b'') for buf in stream: d.update(buf) return d return hashfunc
def p_hash(algo, secret, seed, size): """ Calculate PHASH function Args: algo : Hash algorithm (e.g. sha1, md5, sha256, ...) secret : (Pre-)Master Secret seed : Hash Seed size : Output Size References : * [RFC2246] Section 5. HMAC and the pseudorandom function """ out = bytearray([]) algo = hashlib.__getattribute__(algo.lower()) a = seed while len(out) < size: a = hmac.new(secret, a, algo).digest() out += hmac.new(secret, bytearray(a) + bytearray(seed), algo).digest() return out[:size]
def encrypt_password(self, password, salt=False): algo="sha1" lib = hashlib.__getattribute__(algo) salt = salt if salt else lib(str(random.random())).hexdigest()[:5] hash = lib("%s%s"%(salt, password)).hexdigest() return "%s$%s$%s" % (algo, salt, hash)
def checkio(hashed_string, algorithm): return hashlib.__getattribute__(algorithm)(str(hashed_string.encode('utf-8'))).hexdigest()
#! /usr/bin/env python3 import os, sys, hashlib # algs = hashlib.algorithms_available algs = "blake2b blake2s md5 sha1 sha224 sha256 sha3_224 sha3_256 sha3_384 sha3_512 sha384 sha512" algs = algs.split() msg = "Please provide algorithm name and string.\n algorithms: %s" % " ".join( algs) if len(os.sys.argv) != 3: print(msg, file=sys.stderr) os.sys.exit(2) alg, string = os.sys.argv[1].lower(), os.sys.argv[2] if alg not in algs: print("invalid hash algorithms", file=sys.stderr) os.sys.exit(1) m = hashlib.__getattribute__(alg)() m.update(string.encode(encoding='utf-8')) strHash = m.hexdigest() print(strHash + "\n" + strHash.upper())