def generate_oauth_signature(self, method, params, url, key=None): """ Generate OAuth Signature """ string_to_sign = self.get_signature_base_string(method, params, url) if key is None: key = self.get_sign_key(self.consumer_secret) if self.signature_method == 'HMAC-SHA1': hmac_mod = sha1 elif self.signature_method == 'HMAC-SHA256': hmac_mod = sha256 else: raise UserWarning("Unknown signature_method") # print "\nstring_to_sign: %s" % repr(string_to_sign) # print "\nkey: %s" % repr(key) sig = HMAC(StrUtils.to_binary(key), StrUtils.to_binary(string_to_sign), hmac_mod) sig_b64 = binascii.b2a_base64(sig.digest())[:-1] # print "\nsig_b64: %s" % sig_b64 return sig_b64
def prepare(self): logging.warning(self.request.arguments) hash_code = base64.b64encode( HMAC(settings['SECRET_KEY'].encode(), self._get_vk_params_string(), sha256).digest()) decoded_hash_code = hash_code.decode('utf-8')[:-1].replace( '+', '-').replace('/', '_') try: vk_sign = self.get_argument('sign') except MissingArgumentError: logging.info( f"get request without sign: {self.request.arguments} | {self.request.headers} | " f"{self.request.body}") self.send_error(403) return if decoded_hash_code != vk_sign: logging.info( f"get request with wrong sign: {self.request.arguments} | {self.request.headers} | " f"{self.request.body}") self.send_error(403)
def decode(self, token: bytes) -> bytes: try: payload, signature = token.split(b".") except ValueError: raise TokenError("Invalid token") try: payload: bytes = base64.urlsafe_b64decode(payload) # type: ignore except (TypeError, binascii.Error): raise TokenError("Invalid token") try: signature: bytes = base64.urlsafe_b64decode( signature) # type: ignore except (TypeError, binascii.Error): raise TokenError("Invalid token") if not compare_digest(signature, HMAC(self.key, payload, self.algorithm).digest()): # type: ignore raise TokenError("Invalid token") return payload
def test_validate_payload_invalid_x_hub_signature_format(self): """ Test the validation of a GitHub Webhook payload from a request with invalid X-Hub-Signature format. """ # Arrange url = 'https://0bcb332ca10a.eu.ngrok.io/api/git_to_dbfs' encoded_body = 'somebody'.encode() secret = 'somesecret' encoded_secret = secret.encode() signature = HMAC(key=encoded_secret, msg=encoded_body, digestmod=sha1).hexdigest() headers = {'X-Hub-Signature': signature} req = func.HttpRequest(method='POST', url=url, headers=headers, body=encoded_body) # Act result = validate_payload(req, secret) # Assert self.assertFalse(result)
def encrypt_password(password, salt=None): """ 密码加密 :param password: :param salt: :return: """ if salt is None: salt = os.urandom(8) # 64 bits. assert 8 == len(salt) assert isinstance(salt, bytes) assert isinstance(password, str) if isinstance(password, str): password = password.encode('UTF-8') assert isinstance(password, bytes) result = password for i in range(10): result = HMAC(result, salt, sha256).digest() return bytes.decode(base64.b64encode(salt + result))
def get_oauth_url(self): """ Returns the URL with OAuth params """ params = {} if "?" in self.url: url = self.url[:self.url.find("?")] for key, value in urlparse.parse_qsl( urlparse.urlparse(self.url).query): params[key] = value else: url = self.url params["oauth_consumer_key"] = self.consumer_key params["oauth_timestamp"] = int(time()) params["oauth_nonce"] = HMAC( str(time() + randint(0, 99999)).encode(), "secret".encode(), sha1).hexdigest() params["oauth_signature_method"] = "HMAC-SHA256" params["oauth_signature"] = self.generate_oauth_signature(params, url) query_string = urlencode(params) return "%s?%s" % (url, query_string)
def _make_request(self, method, params=None, data=None): """ Sign request. """ if params is None: params = {} params["nonce"] = int(time.time() * 1000) url = self.client.base_url + self.path + "?" + urlencode(params) if data is None: data = {} data = json.dumps(data) sig = b64encode(HMAC(self.client.secret, url + data, sha256).hexdigest()) response = requests.request(method, url, data=data, headers={ "Auth-Signature": sig, "Auth-API-Key": self.client.key, "Accept": "application/json", "Content-Type": "application/json"}) return self._handle_response(response)
def doConnection(self, action=None, req=None, instance_id=False): darazStore = instance_id url = darazStore.api_url key = darazStore.api_key action = action if action else "CreateProduct" format = "json" userId = darazStore.userId method = req if req else 'GET' now = datetime.now().timestamp() test = datetime.fromtimestamp( now, tz=timezone.utc).replace(microsecond=0).isoformat() parameters = { 'UserID': userId, 'Version': "1.0", 'Action': action, 'Format': format, 'Timestamp': test } concatenated = urllib.parse.urlencode(sorted(parameters.items())) data = concatenated.encode('utf-8') parameters['Signature'] = HMAC(key.encode('utf-8'), data, sha256).hexdigest() headers = { 'Content-Type': "application/json", 'Accept': "*/*", 'Connection': "keep-alive", 'cache-control': "no-cache" } try: response = requests.request(method, url, headers=headers, params=parameters) except Exception as e: raise Warning(_(response.text)) return json.loads(response.text)
def is_valid(query: dict, secret: str, user_id: str) -> bool: """ Check VK Apps signature - partial user verification :param dict query: Dictionary with app launch params :param str secret: app_secret """ if not query.get("sign"): print("no sign") return False if user_id != query.get("vk_user_id")[0]: print("mismatch user_id") return False vk_subset = sorted(filter(lambda key: key.startswith("vk_"), query)) if not vk_subset: print("no subset") return False ordered = {k: query[k] for k in vk_subset} hash_code = b64encode( HMAC(secret.encode(), parse.urlencode(ordered, doseq=True).encode(), sha256).digest()).decode("utf-8") if hash_code[-1] == "=": hash_code = hash_code[:-1] fixed_hash = hash_code.replace('+', '-').replace('/', '_') print(query.get("sign")) print(fixed_hash) return query.get("sign")[0] == fixed_hash
def app_sign(self,secret:'加密密钥'='',data:dict={},sign_func=sha1): '''猜想中的淘宝app加密方法,不过data应该也是要排序什么的吧,不过暂时是不清楚了,逆向不出来 {v=1.0, deviceId=AiXb03Jh5K0C_vSLWC-u2MasOk_76QEfvIpiCMqJKlAl, appKey=21783927, sid=null, t=1545462522, data={"bizType":"taoPassword.judgePassword","bizParam":"{\"passwordContent\":\"comifengnewsclientgold:\\/\\/call?type=list\"}"}, api=mtop.taobao.aplatform.weakget, utdid=XBNj6B3lKccDAOjKwIsds5d9, x-features=27, uid=null, ttid=10035437@etao_android_8.8.8} 现在已找到参数组合顺序 ''' def resovle(key_name): if data.get(key_name) == 'null': return '' elif not isinstance(data.get(key_name,''),str): dumpStr = json.dumps(data.get(key_name),separators=(',',':')) if key_name == 'data': return md5(dumpStr.encode()).hexdigest() else: return dumpStr else: return data.get(key_name,'') keyword_ls = ['utdid','uid','reqbiz-ext','appKey','data','t','api','v','sid','ttid','deviceId','lat','lng','x-features'] if data.get('extdata'): keyword_ls.insert(-1,'extdata') dt = list(map(resovle,keyword_ls)) sign_str = '&'.join(dt) return HMAC(f'{secret}'.encode('utf-8'),sign_str.encode('utf-8'))
def encrypt(password, salt=None): password = password.encode('utf-8') print(password) result = password if salt is None: salt = os.urandom(8) # 64 bits # print(salt) # python assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假。可以理解assert断言语句为raise - if - not,用来测试表示式,其返回值为假,就会触发异常 # assert 8 == len(salt) # isinstance(s, unicode): 判断s是否是unicode编码,如果是就返回true, 否则返回false # assert isinstance(salt, str) # if isinstance(password, unicode): # password = password.encode('utf-8') # print(password) # # assert isinstance(password, str) # # result = password for i in range(10): result = HMAC(result, salt, sha256).digest() print(result) return salt + result
def xmprv_from_seed(seed: Octets, version: Octets) -> bytes: """derive the master extended private key from the seed""" if isinstance(version, str): # hex string version = bytes.fromhex(version) if version not in PRV: m = f"invalid private version ({version})" raise ValueError(m) # serialization data xmprv = version # version xmprv += b'\x00' # depth xmprv += b'\x00\x00\x00\x00' # parent pubkey fingerprint xmprv += b'\x00\x00\x00\x00' # child index # actual extended key (key + chain code) derivation if isinstance(seed, str): # hex string seed = bytes.fromhex(seed) hd = HMAC(b"Bitcoin seed", seed, sha512).digest() mprv = int_from_octets(hd[:32]) xmprv += hd[32:] # chain code xmprv += b'\x00' + mprv.to_bytes(32, 'big') # private key return base58.encode_check(xmprv)
def bip32_crack(parent_xpub: octets, child_xprv: octets) -> bytes: parent_xpub = b58decode_check(parent_xpub, 78) assert parent_xpub[45] in (2, 3), "extended parent key is not a public one" child_xprv = b58decode_check(child_xprv, 78) assert child_xprv[45] == 0, "extended child key is not a private one" # check depth assert child_xprv[4] == parent_xpub[4] + \ 1, "wrong child/parent depth relation" # check fingerprint Parent_bytes = parent_xpub[45:] assert child_xprv[5:9] == h160( Parent_bytes)[:4], "not a child for the provided parent" # check normal derivation child_index = child_xprv[9:13] assert child_index[0] < 0x80, "hardened derivation" parent_xprv = child_xprv[:4] # version parent_xprv += parent_xpub[4:5] # depth parent_xprv += parent_xpub[5:9] # parent pubkey fingerprint parent_xprv += parent_xpub[9:13] # child index parent_chain_code = parent_xpub[13:45] parent_xprv += parent_chain_code # chain code h = HMAC(parent_chain_code, Parent_bytes + child_index, sha512).digest() offset = int.from_bytes(h[:32], 'big') child = int.from_bytes(child_xprv[46:], 'big') parent = (child - offset) % ec.n parent_bytes = b'\x00' + parent.to_bytes(32, 'big') parent_xprv += parent_bytes # private key return b58encode_check(parent_xprv)
def verify_signature(request): payload = request.data headers = request.headers secret_key = app.config["GIT_HUB_WEBHOOK_TOKEN"].encode() if "X-Hub-Signature" in headers: signature_header = headers["X-Hub-Signature"] if "=" in signature_header: sha_name, received_signature = signature_header.split("=") else: raise WrongSignatureType() else: raise NoSignature() if sha_name != "sha1": raise WrongDigestMode() excepted_signature = HMAC(secret_key, payload, "sha1").hexdigest() if app.config["ENV"] != "PRODUCTION": app.logger.info(f"Received signature: {received_signature}") app.logger.info(f"Excepeted signature: {excepted_signature}") return compare_digest(excepted_signature, received_signature)
def Signature(concatenated): sign = HMAC(config.PRIVATE_KEY, concatenated, hashlib.sha256).hexdigest() return sign
def hash_password(salt, paragraph): return HMAC(salt, paragraph, sha1).digest()
def compute_hmac(key, message, digest_class): return HMAC(key, message, digest_class).digest()
def _pbkdf_sha256(password, salt, iterations=NUM_ITERATIONS): result = password.encode("utf-8") for i in xrange(iterations): result = HMAC(result, salt, sha256).digest() return result
def sign_data(secret, data): return b64encode(str(HMAC(secret, data, sha512).digest()))
def generate_device_key(registrationId, masterKey): '''Creates a device derived key by hashing the device unique registrationId with the DPS key.''' deviceKey = b64encode( HMAC(b64decode(masterKey), registrationId.encode('utf-8'), sha256).digest()) return deviceKey.decode('UTF-8')
def hash_entity(entity, hashed_size, salt_param=None): salt_var = salt_param or salt() return b64encode(HMAC(salt_var, entity).digest())[:hashed_size]
def hashID(uid): return HMAC(SECRET, uid).hexdigest()
def ckd(xparentkey: Octets, index: Union[Octets, int]) -> bytes: """Child Key Derivation (CDK) Key derivation is normal if the extended parent key is public or child_index is less than 0x80000000. Key derivation is hardened if the extended parent key is private and child_index is not less than 0x80000000. """ if isinstance(index, int): index = index.to_bytes(4, 'big') elif isinstance(index, str): # hex string index = bytes.fromhex(index) if len(index) != 4: raise ValueError(f"a 4 bytes int is required, not {len(index)}") xparent = base58.decode_check(xparentkey, 78) version = xparent[:4] # serialization data xkey = version # version xkey += (xparent[4] + 1).to_bytes(1, 'big') # (increased) depth if (version in PUB): if xparent[45] not in (2, 3): # not a compressed public key raise ValueError("version/key mismatch in extended parent key") Parent_bytes = xparent[45:] Parent = point_from_octets(ec, Parent_bytes) xkey += h160(Parent_bytes)[:4] # parent pubkey fingerprint if index[0] >= 0x80: raise ValueError("no private/hardened derivation from pubkey") xkey += index # child index parent_chain_code = xparent[13:45] # normal derivation # actual extended key (key + chain code) derivation h = HMAC(parent_chain_code, Parent_bytes + index, sha512).digest() offset = int.from_bytes(h[:32], 'big') Offset = mult(ec, offset) Child = ec.add(Parent, Offset) Child_bytes = octets_from_point(ec, Child, True) xkey += h[32:] # chain code xkey += Child_bytes # public key elif (version in PRV): if xparent[45] != 0: # not a private key raise ValueError("version/key mismatch in extended parent key") parent = int.from_bytes(xparent[46:], 'big') Parent = mult(ec, parent) Parent_bytes = octets_from_point(ec, Parent, True) xkey += h160(Parent_bytes)[:4] # parent pubkey fingerprint xkey += index # child index # actual extended key (key + chain code) derivation parent_chain_code = xparent[13:45] if (index[0] < 0x80): # normal derivation h = HMAC(parent_chain_code, Parent_bytes + index, sha512).digest() else: # hardened derivation h = HMAC(parent_chain_code, xparent[45:] + index, sha512).digest() offset = int.from_bytes(h[:32], 'big') child = (parent + offset) % ec.n child_bytes = b'\x00' + child.to_bytes(32, 'big') xkey += h[32:] # chain code xkey += child_bytes # private key else: raise ValueError("invalid extended key version") return base58.encode_check(xkey)
def access_server(method, ctx, postfix, json_data=None, echo=True, **kwargs): if ctx.obj.get('init', False): sess = requests.Session() stream = kwargs.pop('stream', sess.stream) prepped = requests.Request(method, '/'.join([ctx.obj['server_url'], postfix]), json=json_data, **kwargs).prepare() if ctx.obj.get('app_key') and ctx.obj.get('secret_key'): timestamp = str(round(time() * 1000)) nonce = str(uuid1()) signature = b64encode( HMAC( ctx.obj['secret_key'].encode('ascii'), b'\n'.join([ timestamp.encode('ascii'), nonce.encode('ascii'), ctx.obj['app_key'].encode('ascii'), prepped.path_url.encode('ascii'), prepped.body if json_data else b'', urlencode(sorted(kwargs['data'].items()), quote_via=quote, safe='-._~').encode('ascii') if kwargs.get('data') and isinstance(kwargs['data'], dict) else b'', ]), 'sha1').digest()).decode('ascii') prepped.headers.update({ 'TIMESTAMP': timestamp, 'NONCE': nonce, 'APP_KEY': ctx.obj['app_key'], 'SIGNATURE': signature, }) try: response = sess.send(prepped, stream=stream) if echo: prettify(response) return else: return response except Exception as e: exc_type, exc_value, exc_traceback_obj = sys.exc_info() response = { 'retcode': 100, 'retmsg': str(e), 'traceback': traceback.format_exception(exc_type, exc_value, exc_traceback_obj) } if 'Connection refused' in str(e): response[ 'retmsg'] = 'Connection refused. Please check if the fate flow service is started' del response['traceback'] if 'Connection aborted' in str(e): response['retmsg'] = 'Connection aborted. Please make sure that the address of fate flow server ' \ 'is configured correctly. The configuration file path is: ' \ '{}.'.format(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'settings.yaml'))) del response['traceback'] if echo: prettify(response) return else: return Response(json.dumps(response), status=500, mimetype='application/json') else: response = { 'retcode': 100, 'retmsg': "Fate flow CLI has not been initialized yet or configured incorrectly. " "Please initialize it before using CLI at the first time. And make sure " "the address of fate flow server is configured correctly. The configuration " "file path is: {}.".format( os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'settings.yaml'))) } if echo: prettify(response) else: return Response(json.dumps(response), status=500, mimetype='application/json')
def generate_nonce(): """ Generate nonce number """ nonce = ''.join([str(randint(0, 9)) for i in range(8)]) return HMAC(nonce.encode(), "secret".encode(), sha1).hexdigest()
def create_hmac(secret, str_to_encode): new_hmac = HMAC(secret.encode(encoding=utf8), str_to_encode.encode(encoding=utf8), hashlib.sha256) return b64encode(new_hmac.digest())
def hmac_from_name(alg_name='sha256'): assert alg_name in hashlib.algorithms, "Hash algorithm %s not known" % alg_name alg_constructor = getattr(hashlib, alg_name) return lambda key, msg=None: HMAC(key, msg, alg_constructor)
seed = 0x000102030405060708090a0b0c0d0e0f seed_bytes = 16 print("Seed:", hex(seed), "\nbytes:", seed_bytes) # ==master ext private key== # depth: 0x00 for master nodes, 0x01 for level-1 derived keys, ... depth = b'\x00' # This is ser32(i) for i in xi = xpar/i, with xi the key being serialized. (0x00000000 if master key) child_number = b'\x00\x00\x00\x00' # the fingerprint of the parent's public key (0x00000000 if master key) fingerprint = b'\x00\x00\x00\x00' idf = depth + fingerprint + child_number # master private key, master public key, chain code hd = HMAC(b"Bitcoin seed", seed.to_bytes(seed_bytes, byteorder='big'), sha512).digest() qbytes = hd[:32] q = int(qbytes.hex(), 16) % ec.n qbytes = b'\x00' + q.to_bytes(32, byteorder='big') Q = mult(ec, q, ec.G) Qbytes = octets_from_point(ec, Q, True) chain_code = hd[32:] #extended keys ext_prv = encode_check(xprv + idf + chain_code + qbytes) print("\nm") print(ext_prv) ext_pub = encode_check(xpub + idf + chain_code + Qbytes) print("M") print(ext_pub) assert ext_prv == b"xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", "failure"
seed = 0x4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be seed_bytes = 64 print("Seed:", hex(seed), "\nbytes:", seed_bytes) # ==master ext private key== # depth: 0x00 for master nodes, 0x01 for level-1 derived keys, ... depth = b'\x00' # This is ser32(i) for i in xi = xpar/i, with xi the key being serialized. (0x00000000 if master key) child_number = b'\x00\x00\x00\x00' # the fingerprint of the parent's public key (0x00000000 if master key) fingerprint = b'\x00\x00\x00\x00' idf = depth + fingerprint + child_number # master private key, master public key, chain code hashValue = HMAC(b"Bitcoin seed", seed.to_bytes(seed_bytes, 'big'), sha512).digest() p_bytes = hashValue[:32] p = int(p_bytes.hex(), 16) % ec.order p_bytes = b'\x00' + p.to_bytes(32, 'big') P = ec.pointMultiply(p) P_bytes = (b'\x02' if (P[1] % 2 == 0) else b'\x03') + P[0].to_bytes(32, 'big') chain_code = hashValue[32:] #extended keys ext_prv = b58encode_check(xprv + idf + chain_code + p_bytes) print("\nm") print(ext_prv) ext_pub = b58encode_check(xpub + idf + chain_code + P_bytes) print("M") print(ext_pub) assert ext_prv == b"xprv9s21ZrQH143K25QhxbucbDDuQ4naNntJRi4KUfWT7xo4EKsHt2QJDu7KXp1A3u7Bi1j8ph3EGsZ9Xvz9dGuVrtHHs7pXeTzjuxBrCmmhgC6", "failure"
def generate_nonce(cls): """ Generate nonce number """ if cls.force_nonce is not None: return cls.force_nonce nonce = ''.join([str(randint(0, 9)) for i in range(8)]) return HMAC(nonce.encode(), "secret".encode(), sha1).hexdigest()