def CheckString(check): gntkrjngrkt = hmac.new(key, check[:-32], hashlib.sha256) HM3 = hmac.new(key, check[:-32], hashlib.sha256) if hmac.compare_digest(HM3.digest(), check[-32:]) == True: pas = 1 else: sys.exit(1)
def raw_bip32_ckd(rawtuple, i): vbytes, depth, fingerprint, oldi, chaincode, key = rawtuple i = int(i) if vbytes in PRIVATE: priv = key pub = privtopub(key) else: pub = key if i >= 2**31: if vbytes in PUBLIC: raise Exception("Can't do private derivation on public key!") I = hmac.new(chaincode, b'\x00'+priv[:32]+encode(i, 256, 4), hashlib.sha512).digest() else: I = hmac.new(chaincode, pub+encode(i, 256, 4), hashlib.sha512).digest() if vbytes in PRIVATE: newkey = add_privkeys(I[:32]+B'\x01', priv) fingerprint = bin_hash160(privtopub(key))[:4] if vbytes in PUBLIC: newkey = add_pubkeys(compress(privtopub(I[:32])), key) fingerprint = bin_hash160(key)[:4] return (vbytes, depth + 1, fingerprint, i, I[32:], newkey)
def encrypt_message(pubkey, message, display_only): pk = tools.public_key_to_point(pubkey) if not ecdsa.ecdsa.point_is_valid(ecdsa.ecdsa.generator_secp256k1, pk.x(), pk.y()): raise Exception('invalid pubkey') deter = hmac.new(message, pubkey, sha512).digest() secexp, iv = deter[:32], deter[32:48] ephemeral_exponent = ecdsa.util.number_to_string(ecdsa.util.string_to_number(secexp), ecdsa.ecdsa.generator_secp256k1.order()) ephemeral = tools.EcKey(ephemeral_exponent) ecdh_key = (pk * ephemeral.privkey.secret_multiplier).x() ecdh_key = ('%064x' % ecdh_key).decode('hex') if display_only: ecdh_key += '\x00' key = sha512(ecdh_key).digest() key_e, key_m = key[:32], key[32:] assert len(message) % 16 == 0 aes = pyaes.AESModeOfOperationCBC(key=key_e, iv=iv) ciphertext = ''.join([aes.encrypt(message[i:i+16]) for i in range(0, len(message), 16)]) ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex') encrypted = 'BIE1' + ephemeral_pubkey + iv + ciphertext mac = hmac.new(key_m, encrypted, sha256).digest() return encrypted + mac
def computeSignature(self, password): configXMLString = self.getXMLContents() # ugly removal of spaces because minidom cannot remove them automatically when removing a node configXMLString = re.sub(' <uam_dir>', '<uam_dir>', configXMLString) configXMLString = re.sub('</uam_dir>\n', '</uam_dir>', configXMLString) doc = xml.dom.minidom.parseString(configXMLString) # Remove <uam_dir> node because new GSAs expect so uamdirNode = doc.getElementsByTagName("uam_dir").item(0) uamdirNode.parentNode.removeChild(uamdirNode) uardataNode = doc.getElementsByTagName("uar_data").item(0) uardataB64contents = uardataNode.firstChild.nodeValue.strip()+'\n' if uardataB64contents != "\n": log.debug("UAR data contains data. Must be 7.0 or newer") # replace <uar_data> node with "/tmp/tmp_uar_data_dir,hash" # 1: Strip additional spaces at the end but we need the new line # to compute hash. # "AAAAAAAAAA==\n ]]></uar_data>" <-- 10 spaces uardataHash = hmac.new(password, uardataB64contents, hashlib.sha1).hexdigest() # 2: Replace to <dummy file name, hash> with additional whitespaces. uardataNode.firstChild.nodeValue = ("\n/tmp/tmp_uar_data_dir," + "%s\n ") % (''+uardataHash) log.debug("uar_data is replaced to %s" % uardataNode.toxml()) # Get <config> node configNode = doc.getElementsByTagName("config").item(0) # get string of Node and children (as utf-8) configNodeXML = configNode.toxml() # Create new HMAC using user password and configXML as sum contents return hmac.new(password, configNodeXML, hashlib.sha1).hexdigest()
def __init__(self, app_id, app_secret, access_token): """ Initializes and populates the instance attributes with app_id, app_secret, access_token, appsecret_proof, and requests given arguments app_id, app_secret, and access_token. """ self.app_id = app_id self.app_secret = app_secret self.access_token = access_token if version_info < (3, 0): h = hmac.new( bytes(self.app_secret), msg=bytes(self.access_token), digestmod=hashlib.sha256 ) else: h = hmac.new( bytes(self.app_secret, 'utf-8'), msg=bytes(self.access_token, 'utf-8'), digestmod=hashlib.sha256 ) self.appsecret_proof = h.hexdigest() self.requests = requests.Session() self.requests.verify = os.path.join( os.path.dirname(__file__), 'fb_ca_chain_bundle.crt', ) self.requests.params.update({ 'access_token': self.access_token, 'appsecret_proof': self.appsecret_proof, })
def _tls1_hash(md, sec, seed, olen): """ ssl.c tls1_P_hash """ A1 = hmac.new(key=sec, msg=seed, digestmod=md).digest() chunk = md().digest_size log.debug("tls_hash sec: %s", shex(sec)) log.debug("tls_hash seed: %s", shex(seed)) i = 0 out = bytearray() while True: ctx = hmac.new(key=sec, digestmod=md) ctx_tmp = hmac.new(key=sec, digestmod=md) ctx.update(A1) ctx_tmp.update(A1) ctx.update(seed) if olen > chunk: out[(i * chunk):((i + 1) * chunk)] = ctx.digest() olen -= chunk i += 1 A1 = ctx_tmp.digest() else: A1 = ctx.digest() out[(i * chunk):((i + 1) * chunk)] = A1 break log.debug("tls_hash out: %s", shex(out)) return bytes(out)
def test_constructor(self): hmac_hashfunc = lambda msg: hmac.new(b'mysecretkey', msg) password = Password(hashfunc=hmac_hashfunc) password.set('foo') self.assertEquals(password.str, hmac.new(b'mysecretkey', b'foo').hexdigest())
def _test_etag_is_at_not_duplicated(self, method): # verify only one occurrence of X-Object-Sysmeta-Crypto-Etag-Mac in # X-Backend-Etag-Is-At key = fetch_crypto_keys()['object'] env = {CRYPTO_KEY_CALLBACK: fetch_crypto_keys} req = Request.blank( '/v1/a/c/o', environ=env, method=method, headers={'If-Match': '"an etag"', 'If-None-Match': '"another etag"'}) self.app.register(method, '/v1/a/c/o', HTTPOk, {}) resp = req.get_response(self.encrypter) self.assertEqual('200 OK', resp.status) self.assertEqual(1, len(self.app.calls), self.app.calls) self.assertEqual(method, self.app.calls[0][0]) actual_headers = self.app.headers[0] self.assertIn('X-Backend-Etag-Is-At', actual_headers) self.assertEqual('X-Object-Sysmeta-Crypto-Etag-Mac', actual_headers['X-Backend-Etag-Is-At']) self.assertIn('"%s"' % base64.b64encode( hmac.new(key, 'an etag', hashlib.sha256).digest()), actual_headers['If-Match']) self.assertIn('"another etag"', actual_headers['If-None-Match']) self.assertIn('"%s"' % base64.b64encode( hmac.new(key, 'another etag', hashlib.sha256).digest()), actual_headers['If-None-Match'])
def _send_request(self, api_url, params={}, extra_headers=None): nonce = str(self._create_nonce()) params['nonce'] = nonce message = urllib.parse.urlencode(params) if sys.version_info.major == 2: signature = hmac.new(self.api_secret, msg=message, digestmod=hashlib.sha512).hexdigest() else: signature = hmac.new(str.encode(self.api_secret), msg=str.encode(message), digestmod=hashlib.sha512).hexdigest() headers = { 'Content-type': "application/x-www-form-urlencoded", 'key': self.api_key, 'sign': signature } if extra_headers is not None: for k, v in extra_headers.items(): headers[k] = v response = requests.post(api_url, data=message, headers=headers) code = response.status_code if code == 200: if 'error' in response.json(): return False, response.json()['error'] else: return response.json() return None
def get_signed_url(self): """ build signed parameters following http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html """ keys = sorted(self.url_params) values = map(self.url_params.get, keys) url_string = urlencode(list(zip(keys, values))) string_to_sign = "GET\n%s\n/\n%s" % (self.base_url, url_string) try: if sys.version_info[:2] == (2, 5): signature = hmac.new(key=self.secret_key, msg=string_to_sign, digestmod=hashlib.sha256).digest() else: signature = hmac.new( key=bytes(self.secret_key), msg=bytes(string_to_sign), digestmod=hashlib.sha256 ).digest() except TypeError: signature = hmac.new( key=bytes(self.secret_key, "utf-8"), msg=bytes(string_to_sign, "utf-8"), digestmod=hashlib.sha256 ).digest() signature = base64.encodestring(signature).strip() urlencoded_signature = quote_plus(signature) url_string += "&Signature=%s" % urlencoded_signature return "/?" + url_string
def hmac(self, counter=None, key=None, challenge=None): """ :param counter: :param key: :param challenge: The datainput for OCRA :type challenge: hex string :return: """ # log.error("hmacSecret()") if counter is None: counter = self.counter # When using a counter, we can only use 64bit as data_input. # When we allow a raw data_input, we could use 160bit or more. if not challenge: data_input = struct.pack(">Q", counter) else: data_input = binascii.unhexlify(challenge) if key is None: dig = str(self.secretObj.hmac_digest(data_input, self.hashfunc)) else: if pver > 2.6: dig = hmac.new(key, data_input, self.hashfunc).digest() else: dig = hmac.new(key, str(data_input), self.hashfunc).digest() return dig
def server_post_decrypt(self, buf): if self.raw_trans: return (buf, False) self.recv_buf += buf out_buf = b'' if not self.has_recv_header: if len(self.recv_buf) < 2: return (b'', False) if (ord(self.recv_buf[0]) & 0x10) != 0x10: return self.not_match_return(self.recv_buf) head_size = self.get_head_size(self.recv_buf, 65536) if len(self.recv_buf) < head_size + 10: return self.not_match_return(self.recv_buf) sha1data = hmac.new(self.server_info.recv_iv + self.server_info.key, self.recv_buf[:head_size], hashlib.sha1).digest()[:10] if sha1data != self.recv_buf[head_size:head_size + 10]: logging.error('server_post_decrype data uncorrect auth HMAC-SHA1') return self.not_match_return(self.recv_buf) out_buf = to_bytes(chr(ord(self.recv_buf[0]) & 0xEF)) + self.recv_buf[1:head_size] self.recv_buf = self.recv_buf[head_size + 10:] self.has_recv_header = True while len(self.recv_buf) > 2: length = struct.unpack('>H', self.recv_buf[:2])[0] + 12 if length > len(self.recv_buf): break data = self.recv_buf[12:length] sha1data = hmac.new(self.server_info.recv_iv + struct.pack('>I', self.recv_id), data, hashlib.sha1).digest()[:10] if sha1data != self.recv_buf[2:12]: raise Exception('server_post_decrype data uncorrect chunk HMAC-SHA1') self.recv_id = (self.recv_id + 1) & 0xFFFFFFFF out_buf += data self.recv_buf = self.recv_buf[length:] return (out_buf, False)
def sso_handler(self): if local.user is None: return 'Unauthorized' payload = local.data['payload'] sig = local.data['sig'] computed_sig = hmac.new( config.get("core", "secret").encode(), payload.encode(), hashlib.sha256).hexdigest() if computed_sig != sig: return 'Bad request' # Get nonce. payload_decoded = b64decode(payload).decode() d = dict(nonce.split("=") for nonce in payload_decoded.split('&')) # Prepare response. response_data = dict() response_data['nonce'] = d['nonce'] response_data['external_id'] = local.user.username response_data['username'] = local.user.username response_data['email'] = local.user.email # Build final url. res_payload = urllib.urlencode(response_data) res_payload = b64encode(res_payload.encode()) sig = hmac.new( config.get("core", "secret").encode(), res_payload, hashlib.sha256).hexdigest() local.resp['parameters'] = urllib.urlencode({ 'sso': res_payload, 'sig': sig })
def get_request_url(command_str , args ): baseurl='http://172.16.206.143:8080/client/api?' request={} #request['command']='listUsers' #below is private api under cloudstack 4.0.2 #request['command']='createVMSnapshot' #request['vmid']='50e9dbdd-2efe-4df0-8478-581fd43088ce' request['command'] = command_str if args is not None: for k,v in args.iteritems(): request[k]=v #request['response']='xml' request['response']='json' request['apikey']='' secretkey='' request_str='&'.join(['='.join([k,urllib.quote_plus(request[k])]) for k in request.keys()]) sig_str='&'.join(['='.join([k.lower(),urllib.quote_plus(request[k].lower().replace('+','%20'))])for k in sorted(request.iterkeys())]) sig=hmac.new(secretkey,sig_str,hashlib.sha1) sig=hmac.new(secretkey,sig_str,hashlib.sha1).digest() sig=base64.encodestring(hmac.new(secretkey,sig_str,hashlib.sha1).digest()) sig=base64.encodestring(hmac.new(secretkey,sig_str,hashlib.sha1).digest()).strip() sig=urllib.quote_plus(base64.encodestring(hmac.new(secretkey,sig_str,hashlib.sha1).digest()).strip()) req=baseurl+request_str+'&signature='+sig return req
def encrypt(key, messagetype, data, nonce): # if (fRC4_EXP){ # *((DWORD *)(L40+10)) = T; # HMAC (K, L40, 10 + 4, K1); # }else{ # HMAC (K, &T, 4, K1); # } K1 = hmac.new(key, chr(messagetype) + "\x00\x00\x00", hashlib.md5).digest() # \x0b = 11 # memcpy (K2, K1, 16); K2 = K1 # if (fRC4_EXP) memset (K1+7, 0xAB, 9); # add_8_random_bytes(data, data_len, conf_plus_data); ddata = nonce + data # HMAC (K2, conf_plus_data, 8 + data_len, checksum); checksum = hmac.new(K2, ddata, hashlib.md5).digest() # HMAC (K1, checksum, 16, K3); K3 = hmac.new(K1, checksum, hashlib.md5).digest() #print "K3: %s" % K3.encode('hex') # RC4(K3, conf_plus_data, 8 + data_len, edata + 16); # print "EN DDATA: %s" % ddata[:32].encode('hex') edata = rc4crypt(K3, ddata) # memcpy (edata, checksum, 16); # edata_len = 16 + 8 + data_len; return checksum + edata
def _derive_key(self, key, magic): hash1 = hmac.new(key, magic, sha1).digest() hash2 = hmac.new(key, hash1 + magic, sha1).digest() hash3 = hmac.new(key, hash1, sha1).digest() hash4 = hmac.new(key, hash3 + magic, sha1).digest() return hash2 + hash4[0:4]
def add_auth(self, request): timestamp = datetime.utcnow().strftime('%Y%m%dT%H%M%SZ') request.headers['X-Amz-Date'] = timestamp if self.session_token: request.headers['X-Amz-Security-Token'] = self.session_token # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html canonical_headers = ''.join('{0}:{1}\n'.format(k.lower(), request.headers[k]) for k in sorted(request.headers)) signed_headers = ';'.join(k.lower() for k in sorted(request.headers)) payload_hash = sha256(request.body.encode('utf-8')).hexdigest() canonical_request = '\n'.join([request.method, '/', '', canonical_headers, signed_headers, payload_hash]) # https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html algorithm = 'AWS4-HMAC-SHA256' credential_scope = '/'.join([timestamp[0:8], self.region, 'sts', 'aws4_request']) canonical_request_hash = sha256(canonical_request.encode('utf-8')).hexdigest() string_to_sign = '\n'.join([algorithm, timestamp, credential_scope, canonical_request_hash]) # https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html key = 'AWS4{0}'.format(self.secret_key).encode('utf-8') key = hmac.new(key, timestamp[0:8].encode('utf-8'), sha256).digest() key = hmac.new(key, self.region.encode('utf-8'), sha256).digest() key = hmac.new(key, 'sts'.encode('utf-8'), sha256).digest() key = hmac.new(key, 'aws4_request'.encode('utf-8'), sha256).digest() signature = hmac.new(key, string_to_sign.encode('utf-8'), sha256).hexdigest() # https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html authorization = '{0} Credential={1}/{2}, SignedHeaders={3}, Signature={4}'.format( algorithm, self.access_key, credential_scope, signed_headers, signature) request.headers['Authorization'] = authorization
def update_provider(self, provider): self._provider = provider self._hmac = hmac.new(self._provider.secret_key, digestmod=sha) if sha256: self._hmac_256 = hmac.new(self._provider.secret_key, digestmod=sha256) else: self._hmac_256 = None
def pack_auth_data(self, auth_data, buf): data = auth_data data_len = 12 + 4 + 16 + 4 data = data + (struct.pack('<H', self.server_info.overhead) + struct.pack('<H', 0)) mac_key = self.server_info.iv + self.server_info.key check_head = os.urandom(4) self.last_client_hash = hmac.new(mac_key, check_head, self.hashfunc).digest() check_head += self.last_client_hash[:8] if b':' in to_bytes(self.server_info.protocol_param): try: items = to_bytes(self.server_info.protocol_param).split(b':') self.user_key = items[1] uid = struct.pack('<I', int(items[0])) except: uid = os.urandom(4) else: uid = os.urandom(4) if self.user_key is None: self.user_key = self.server_info.key encryptor = encrypt.Encryptor(to_bytes(base64.b64encode(self.user_key)) + self.salt, 'aes-128-cbc', b'\x00' * 16) uid = struct.unpack('<I', uid)[0] ^ struct.unpack('<I', self.last_client_hash[8:12])[0] uid = struct.pack('<I', uid) data = uid + encryptor.encrypt(data)[16:] self.last_server_hash = hmac.new(self.user_key, data, self.hashfunc).digest() data = check_head + data + self.last_server_hash[:4] self.encryptor = encrypt.Encryptor(to_bytes(base64.b64encode(self.user_key)) + to_bytes(base64.b64encode(self.last_client_hash)), 'rc4') return data + self.pack_client_data(buf)
def _generate_url(self, options): options['Service'] = 'AWSECommerceService' options['AWSAccessKeyId'] = self.access_key_id options['AssociateTag'] = self.associate_tag options['Timestamp'] = self._generate_timestamp() # 'None' が含まれている場合は削除する. for k, v in options.items(): if v is None: del options[k] # 署名(v2)を作成する. keys = sorted(options.keys()) args = '&'.join('%s=%s' % (key, urllib2.quote(unicode(options[key]) .encode('utf-8'), safe='~')) for key in keys) msg = 'GET' msg += '\n' + self.uri msg += '\n' + self.end_point msg += '\n' + args hmac.new(self.secret_key or '', msg, hashlib.sha256).digest() signature = urllib2.quote( base64.b64encode(hmac.new(self.secret_key or '', msg, hashlib.sha256).digest())) url = "http://%s%s?%s&Signature=%s" % (self.uri, self.end_point, args, signature) return url
def surl_verify(request): """ Verify a signed URL. The URL must contain the following GET parameters: * *surl_timestamp*: when the url was generated. Must be within the past hour, to avoid permitting old surls. * *surl_token* The access token used to sign the url. * *surl_sig* The computed signature (base-64 encoded sha1) of the url. Will always return :http:statuscode:`200`. The response body will be one of: * ``<result>ok</result>``: The surl was valid. * ``<result>old</result>``: The surl was too old. * ``<result>mismatch</result>``: The surl's signature was invalid. """ OK = HttpResponse("<result>ok</result>", mimetype="application/xml") # May want to add more explanation here OLD = HttpResponse("<result>old</result>", mimetype="application/xml") MISMATCH = HttpResponse("<result>mismatch</result>", mimetype="application/xml") url = request.GET["url"] parsed_url = urlparse.urlparse(url) query = urlparse.parse_qs(parsed_url.query) # check timestamp (cheapest thing to check, we check it first) url_timestamp = iso8601.parse_utc_date(query["surl_timestamp"][0]) if (datetime.datetime.utcnow() - url_timestamp) > datetime.timedelta(hours=1): return OLD # generate the secret that should be used here try: token = AccessToken.objects.get(token=query["surl_token"][0]) except AccessToken.DoesNotExist: return MISMATCH # compute the surl secret # the string conversion on the secret is required because of a python 2.6 bug secret = base64.b64encode(hmac.new(str(token.token_secret), "SURL-SECRET", hashlib.sha1).digest()) # extract the signature surl_sig = query["surl_sig"][0] # remove the signature from the URL to verify the rest of it # technically this means the signature can be inserted in the middle of the URL, # but we'll live with that for now, it shouldn't present a problem url_without_sig = url.replace("&%s" % urllib.urlencode({"surl_sig": surl_sig}), "") expected_signature = base64.b64encode(hmac.new(secret, url_without_sig, hashlib.sha1).digest()) if expected_signature == surl_sig: return OK else: return MISMATCH
def sendall(self, data): if self.connected: if self.__ota: # modified from https://github.com/shadowsocks/shadowsocks/blob/master/shadowsocks/tcprelay.py data_len = struct.pack(">H", len(data)) index = struct.pack('>I', self._ota_chunk_idx) key = self.crypto.cipher_iv + index sha110 = hmac.new(key, data, hashlib.sha1).digest()[:10] self._ota_chunk_idx += 1 data = data_len + sha110 + data self._sock.sendall(self.crypto.encrypt(data)) else: # https://shadowsocks.org/en/spec/one-time-auth.html host, port = self.__address addrtype = 19 if self.__ota else 3 header = b''.join([chr(addrtype), chr(len(host)).encode(), host.encode(), struct.pack(b">H", port)]) if self.__ota: key = self.crypto.cipher_iv + self.crypto.key header += hmac.new(key, header, hashlib.sha1).digest()[:10] self._sock.sendall(self.crypto.encrypt(header)) self.connected = True if data: self.sendall(data)
def send_hmac(*arg): # send_hmac(app, url, request_path, client_ip, json_data) # our shared private key, since this is a single key application we don't need a public key (to add one the verification routine needs to get private key based on public key) secret = arg[0].config['SECRET_KEY'] # what time is it? (unix seconds from epoch) timenow = time.time() # sign JSON message if len(arg) > 3: digester = hmac.new(secret) # the blob we use here is the path of the request that we want to make, the request url, the json data, and the clients timestamp digester.update(arg[2]+str(arg[4])+str(arg[3])+str(timenow)) digest = digester.hexdigest() # and send, including the hash and timestamp so that the hash can be recalculated later headers = {'Content-Type': 'application/json'} r = requests.post(arg[1]+arg[2]+'?timestamp='+str(timenow)+'&hash='+digest, data=json.dumps(arg[3]), headers=headers) return r.json() # sign url message else: digester = hmac.new(secret) digester.update(arg[2]+str(arg[3])+str(timenow)) digest = digester.hexdigest() r = requests.get(arg[1]+arg[2]+'?timestamp='+str(timenow)+'&hash='+digest) return r.json()
def api_url(self, **kwargs): """The URL for making the given query against the API.""" query = { 'Operation': self.Operation, 'Service': "AWSECommerceService", 'Timestamp': time.strftime( "%Y-%m-%dT%H:%M:%SZ", time.gmtime()), 'Version': self.Version, } query.update(kwargs) query['AWSAccessKeyId'] = self.AWSAccessKeyId query['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) if self.AssociateTag: query['AssociateTag'] = self.AssociateTag service_domain = SERVICE_DOMAINS[self.Region][0] quoted_strings = _quote_query(query) data = "GET\n" + service_domain + "\n/onca/xml\n" + quoted_strings if sys.version_info[0] == 3: digest = hmac.new( bytes(self.AWSSecretAccessKey, encoding='utf-8'), bytes(data, encoding='utf-8'), sha256).digest() signature = urllib.parse.quote(b64encode(digest)) else: digest = hmac.new(self.AWSSecretAccessKey, data, sha256).digest() signature = urllib.quote(b64encode(digest)) return ("http://" + service_domain + "/onca/xml?" + quoted_strings + "&Signature=%s" % signature)
def validate_hash(self, unknown_mac): true_mac = hmac.new(self.K, str(self.salt), sha256).hexdigest() if self.mitm: start = time.time() for i, guess in enumerate(open('passwords.txt', 'r').read().splitlines()): xH = sha256(str(self.salt) + guess).hexdigest() x = int('0x' + xH, 16) v = pow(self.g, x, self.N) # not to confuse with self.v S = pow(self.A * pow(v, self.u, self.N), self.b, self.N) K = sha256(str(S)).hexdigest() guess_mac = hmac.new(K, str(self.salt), sha256).hexdigest() if guess_mac == unknown_mac: n = time.time() print "Pwned. Result is", guess print "Computed", i, "hashes in", int(n-start), "sec." print "Throughput", i / (n-start), "guesses / sec." print "Logging on..." pwner = Client(self.N, self.g, self.k, '*****@*****.**', guess, simple=True) pwner.logon_to(self.mitm) return "OK" n = time.time() print "Not pwned." print "Computed", i, "hashes in", int(n-start), "sec." print "Throughput", i / (n-start), "guesses / sec." assert 0 return "OK" if true_mac == unknown_mac: return "OK" else: return "YOU LOSE. GET OFF MY PROPERTY."
def _get_hmac(self, env, expires, key,uid_sig, request_method=None): """ Returns the hexdigest string of the HMAC-SHA1 (RFC 2104) for the request. :param env: The WSGI environment for the request. :param expires: Unix timestamp as an int for when the URL expires. :param key: Key str, from the X-Account-Meta-Temp-URL-Key of the account. :param request_method: Optional override of the request in the WSGI env. For example, if a HEAD does not match, you may wish to override with GET to still allow the HEAD. :returns: hexdigest str of the HMAC-SHA1 for the request. """ if not request_method: request_method = env['REQUEST_METHOD'] if not uid_sig: return hmac.new(key, '%s\n%s\n%s' % (request_method, expires, env['PATH_INFO']), sha1).hexdigest() else: return hmac.new(key, '%s\n%s\n%s\n%s' % (request_method, expires, env['PATH_INFO'],uid_sig), sha1).hexdigest()
def onMessage(self, Connection, Data, Status, Extra): strData = Data.decode("utf-8", "ignore") if (Status == 200): Domoticz.Debug("Good Response received for '"+self.pluginState+"'.") if (self.pluginState == "GetAuth"): challenge = extractTagValue('Challenge', strData).encode() self.sessionCookie = extractTagValue('Cookie', strData) publickey = extractTagValue('PublicKey', strData) loginresult = extractTagValue('LoginResult', strData) encdata = hmac.new((publickey + Parameters["Mode2"]).encode(), challenge, hashlib.md5) self.privateKey = encdata.hexdigest().upper().encode() encdata = hmac.new(self.privateKey, challenge, hashlib.md5) loginpassword = encdata.hexdigest().upper() data = '<?xml version="1.0" encoding="utf-8"?>' + \ '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' + \ '<soap:Body>' + \ '<Login xmlns="http://purenetworks.com/HNAP1/">' + \ '<Action>login</Action>' + \ '<Username>Admin</Username>' + \ '<LoginPassword>' + loginpassword + '</LoginPassword>' + \ '<Captcha></Captcha>' + \ '</Login>' + \ '</soap:Body>' + \ '</soap:Envelope>' headers = { 'Content-Type': 'text/xml; charset=utf-8', 'Accept': 'Content-Type: text/html; charset=UTF-8', \ 'Host': Parameters["Address"]+":"+Parameters["Port"], \ 'User-Agent':'Domoticz/1.0', \ 'SOAPAction' : '"http://purenetworks.com/HNAP1/Login"', \ 'Content-Length' : "%d"%(len(data)), \ 'Cookie' : 'uid=' + self.sessionCookie } self.httpConn.Send(data, 'POST', '/HNAP1/', headers) self.pluginState = "Login" elif (self.pluginState == "Login"): loginresult = extractTagValue('LoginResult', strData) if (loginresult.upper() != "SUCCESS"): Domoticz.Error("Login failed, check username and password in Hardware page") else: Domoticz.Log("Smart plug authentication successful.") self.pluginState = "Ready" elif (self.pluginState == "Ready"): if (strData.find('GetSocketSettingsResult') > 0): opStatus = extractTagValue('OPStatus', strData).upper() if (len(opStatus) and (self.socketOn != opStatus)): self.socketOn = opStatus Domoticz.Log("Socket State has changed, Now: "+self.socketOn) if (self.socketOn == "TRUE"): if (1 in Devices): Devices[1].Update(1,"100") else: if (1 in Devices): Devices[1].Update(0,"0") elif (strData.find('SetSocketSettingsResult') > 0): self.GetSocketSettings() Domoticz.Debug(self.pluginState+": "+strData) else: Domoticz.Debug(self.pluginState+": "+strData) elif (Status == 400): Domoticz.Error("Smart plug returned a Bad Request Error.") elif (Status == 500): Domoticz.Error("Smart plug returned a Server Error.")
def authorize_hmac(app): # single private key application (to add more link to backing store to link public key to private key secret = app.config['SECRET_KEY'] # make sure we were sent the client timestamp and the HMAC hash if request.args.get('hash') and request.args.get('timestamp'): client_hash = request.args.get('hash') # get the timestamp given to us by the client client_timestamp = request.args.get('timestamp') # check that the clients timestamp hasn't expired (timestamp+10 minutes), this helps thwart timing attacks if time.time() < float(client_timestamp)+float(600): # verify json message if request.json: digester = hmac.new(secret) # the blob we use here is the path of the request that was made, the json data, the client remote address, and the clients timestamp digester.update(request.path+str(request.json)+str(request.remote_addr)+str(client_timestamp)) digest = digester.hexdigest() # true if they match, false if they don't return digest == client_hash # verify url var message else: digester = hmac.new(secret) # since all the message payload is in the url we only need to blob the request path, client remote addres, and client timestamp digester.update(request.path+str(request.remote_addr)+str(client_timestamp)) digest = digester.hexdigest() return digest == client_hash else: return False else: return False
def generate_token(client, hash): ''' generate an access-token for a client ''' own_hash = hmac.new(str(client.secret), str(client.pk), sha1 ).hexdigest() print(own_hash) if hash == own_hash: return True rand = random.Random() token = AccessToken() token.client = client.pk token.salt = rand.randint(0, 2 ** 48) token.creation_date = datetime.now() hash = hmac.new( str(client.secret), str('client={}'.format(client.client_id)), sha1, ) hash.update(str('salt={}'.format(token.salt))) hash.update(str('timestamp={}'.format(token.creation_date.isoformat()))) token.access_token = hash.hexdigest() token.active = True if app.debug: print(token.access_token) db.session.add(token) db.session.commit() return token.access_token
def _construct_headers(url): """ Constructs headers to send with request. Internal usage. The Date header needs to be the current date and time of the request in RFC1123 format (e.g. Tue, 04 Sep 2012 15:57:48) The Auth header structure is {public_key}/{digest} where {public_key} is your public key provided by eRepublik and {digest} is a hash that represents an encrypted value of a concatenated string formed from {resource}, {action}, {params} (if they exist), and {date} (the same value Date header has). """ if public_key is None or private_key is None: raise Exception("Invalid keys") header = {"Auth": public_key + "/"} date = strftime("%a, %d %b %Y %H:%M:%S", gmtime()) header["Date"] = date to_digest = (url.replace("/", ":").replace("?", ":") + ":").lower() + date if version_info >= (3, 0): # 3.X behavior is correct. Since HMAC operates on bytes, not text, # only bytes are accepted. In Python 2, the acceptance of # Unicode strings is more an accident than a feature. header["Auth"] += hmac.new(bytes(private_key, "utf-8"), bytes(to_digest, "utf-8"), sha256).hexdigest() else: header["Auth"] += hmac.new(private_key, to_digest, sha256).hexdigest() return header
def get_signature(key, msg): return hmac.new(key.encode(), msg.encode(), hashlib.sha256).hexdigest()
async def get_authenticated_user( self, redirect_uri: str, client_id: str, client_secret: str, code: str, extra_fields: Dict[str, Any] = None, ) -> Optional[Dict[str, Any]]: """Handles the login for the Facebook user, returning a user object. Example usage: .. testcode:: class FacebookGraphLoginHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): async def get(self): if self.get_argument("code", False): user = await self.get_authenticated_user( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], client_secret=self.settings["facebook_secret"], code=self.get_argument("code")) # Save the user with e.g. set_secure_cookie else: await self.authorize_redirect( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], extra_params={"scope": "read_stream,offline_access"}) .. testoutput:: :hide: This method returns a dictionary which may contain the following fields: * ``access_token``, a string which may be passed to `facebook_request` * ``session_expires``, an integer encoded as a string representing the time until the access token expires in seconds. This field should be used like ``int(user['session_expires'])``; in a future version of Tornado it will change from a string to an integer. * ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``, ``link``, plus any fields named in the ``extra_fields`` argument. These fields are copied from the Facebook graph API `user object <https://developers.facebook.com/docs/graph-api/reference/user>`_ .. versionchanged:: 4.5 The ``session_expires`` field was updated to support changes made to the Facebook API in March 2017. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ http = self.get_auth_http_client() args = { "redirect_uri": redirect_uri, "code": code, "client_id": client_id, "client_secret": client_secret, } fields = set([ "id", "name", "first_name", "last_name", "locale", "picture", "link" ]) if extra_fields: fields.update(extra_fields) response = await http.fetch( self._oauth_request_token_url(**args) # type: ignore ) args = escape.json_decode(response.body) session = { "access_token": args.get("access_token"), "expires_in": args.get("expires_in"), } assert session["access_token"] is not None user = await self.facebook_request( path="/me", access_token=session["access_token"], appsecret_proof=hmac.new( key=client_secret.encode("utf8"), msg=session["access_token"].encode("utf8"), digestmod=hashlib.sha256, ).hexdigest(), fields=",".join(fields), ) if user is None: return None fieldmap = {} for field in fields: fieldmap[field] = user.get(field) # session_expires is converted to str for compatibility with # older versions in which the server used url-encoding and # this code simply returned the string verbatim. # This should change in Tornado 5.0. fieldmap.update({ "access_token": session["access_token"], "session_expires": str(session.get("expires_in")), }) return fieldmap
def __sign(self, data): hashed = hmac.new(self.secret, data, sha1) return urlsafe_b64encode(hashed.digest())
recibidos.append(d) print('recibido..\n ' + str(d)) keyword = config.get("S1", "key").encode('utf-8') mensaje = d[0].encode('utf-8') code = d[1].encode('utf-8') hashing = code[0:tam].decode('utf-8') tamCod = len(code) time = code[tam + 1:tamCod].decode('utf-8') digest_maker = hmac.new(keyword, mensaje, cod) digest_maker.update(mensaje) digest = digest_maker.hexdigest() notifi = "OK" if (digest != hashing and time in recibidos): notifi = "ERROR - Integridad violada" out = str(datetime.datetime.now()) + " - " + str( d) + " - " + notifi + " \n" outfile.write(out) if data:
def create_signature(self, secret, *parts): hash = hmac.new(bytes(secret, 'utf8'), digestmod=hashlib.sha1) for part in parts: hash.update(str(part).encode('utf8')) return hash.hexdigest()
#m = hashlib.md5() #m.update(content) #md5value = base64.b64encode(m.digest()).decode('utf-8') #req.add_header('Content-Type', 'text/plain') #req.add_header('Content-MD5', md5value) hstr = '' hstr += 'GET\n' hstr += '\n' hstr += '\n' hstr += timestr + '\n' # hstr += 'x-amz-acl:public-read-write\n' hstr += '/admin/user' #print('hstr:%s' % (hstr,)) key = bytearray(secret_key, 'utf-8') hres = hmac.new(key, hstr.encode('utf-8'), hashlib.sha1).digest() #print('type:%s' % (type(hres, ))) hres = base64.b64encode(hres) hres = hres.decode('utf-8') #print('hres:%s' % (hres,)) req.add_header('Authorization', 'AWS ' + access_key + ':' + hres) with urllib.request.urlopen(req) as f: print(f.status) # print(f.read().decode('utf-8'))
def create_sig(api_secret, message): _hmac = hmac.new(api_secret.encode('latin-1'), msg=message, digestmod=hashlib.sha256) signature = _hmac.digest() signature = base64.b64encode(signature).decode("utf-8") return signature
def verify_token(token): return hmac.new( TOKEN_SECRET, token[:-TOKEN_SALT_SIZE].encode(), 'sha256').hexdigest()[:TOKEN_SALT_SIZE] == token[-TOKEN_SALT_SIZE:]
def getLoginCookiesXg(username, password): deviceId = '1E6B1539-D151-4D0F-9E12-92516BB60B3D' randomPwd = 'sKsB4hXIhXaDa1r0' # aes秘钥 password_key = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvIYZvc4oZKA26ukUXHR8C5Szfmwk1V5E5EyW5BPyiYL5bpKKYNbAsgXyCZCIOwx4B8DsGpACax8 0EqeJ43NAarGH4zqXUHNbTNnvSpFr4EYmnMegSG7KpAZ9CjY19c6SaEfAopA7/Td+BWCqE6z4G+gSLBboDhRFtFtbrgjumbjkkwaAweuRib/Nzm6FV6ixk5 mCAdAZ8bXcgtG0Cp0k4m0AXMwMza5Nt/yV+gCzwqH746WvVZWnFHsST4MohFq2kncu2fAWFo5uUI5RsBY4JHcG4/U9TV43vwQHiiY5dw/V5ZnvtHRBQ2mSN 6yi0ez7yh0YV+7nMfrbZKb5u+aKIwIDAQAB -----END PUBLIC KEY-----""" ftpgs_key = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA348XeSOeOz3Lgfq7oIMv35MN6yPCrpiSkRjDcDYBgZW4m6VbJ2ALzqfM7bb+08A/5CRH2DERJ/s OgaCL2grmdu2I2mqsPq+kUecPIs+aXdmwIOX42IDgGJYM3Wtifc7A0ApFnqww2x0FL83fhli5Nm7wTwrP/1yxb/zpjrowzlBxglGYNHWSsNGQCft0zLe/UI U2PK8zLTCZAtyasETxMcqiCIuqbgZ04WCdiWqUO7EghK8nMfrV8CRzofTjPmcAZK3tI5crE8ImOXt2QtP3uOrJXIlwI6bTC+fYswgC/Co6HocvfI1fMSSFg KDGWLiSK1Yt4Qt9SepGDTrJNc90NwIDAQAB -----END PUBLIC KEY-----""" '''生成参数data''' '''生成滑块token函数''' def slide_token(): t = time.strftime("%y%m%d%H%M%S", time.localtime()) print("t:", t) strone = "0^123^1080,1776^-^-^1%s^-^10.25.23.37^5.1^352136063328633" % ( t) strtwo = "%sslide" % (strone) strthree = generateMD5(strtwo) # 调用MD5加密函数 a = strthree.replace('a', 'A').replace('b', 'B').replace('c', 'C').replace( 'd', 'D').replace('e', 'E').replace('f', 'F') strfour = a + '_' + strone strfive = base64.b64encode(strfour.encode('utf-8')) strlast = str(strfive, 'utf-8') return strlast print(slide_token()) print('断点') newstr = slide_token() print('newstr:', newstr) rsa_text = generateRSA(password_key, password) print('rsa_text:', rsa_text) headers_login = { "User-Agent": "SNYifubao/6.6.25 (iPhone; iPhone iOS 12.1.4; Scale/3.00)", "Content-Type": "application/x-www-form-urlencoded", "Connection": "keep-alive", "deviceId": "1E6B1539-D151-4D0F-9E12-92516BB60B3D", "terminal": "12", "et": "1", "terminalType": "EPP_IOS", "eppVersion": "6.6.25", "appToken": "4d5f5851049df04f430bdc5086daa903b298db7e" } u1 = str(uuid.uuid4()) u1 = u1.replace('-', '') print(u1) time_start = time.time() # time.time()为1970.1.1到当前时间的毫秒数 print(time_start) time_start = str(time_start).replace(".", "") time_start = time_start[0:13] print("time_start:", time_start) gsBizNo = u1 + "_" + time_start print("gsBizNo:", gsBizNo) parameters = str({ "deviceId": "1E6B1539-D151-4D0F-9E12-92516BB60B3D", "shumeiDeviceId": "2019052114563375c760ca5e036461d24f40a05d97dc8b0119631b1a57c8e6", "userName": username, "clientMAC": "", "verifyCode": "", "password": rsa_text, "gsBizNo": gsBizNo, "sillerToken": newstr + "^IAR^488872E4A185335D9A8CB77C58F09147671860543E71E21E6423423DDB3504D31777B11104600B88CD34072354BCEAF18A4D3B3FEE3435719B7FAFD3A01FA8B165A" "5A646FC3722A23F29B4C6AAC5588F11E9C9844DB3B93638110E153097F62EA4F5715835A03335524BFD3328A26E24478991EA9788D287C413EFBC89D99D97EA7F864D502B" "A00888996C1AB052EE94793D617A8DE36B87C02BB789BC6D18D22DAE6792B385055546D2F78B30A62AC62FB35FE0A209B85F265C0976F370995E190E61F3F20EDFC63699D" "19E78FA852EE411D7C011DB7F9E431C4486CCD862E18A4D3B3FEE3435713000ECA2A3AF5A70B2504726D698BCD0642E138238C8B3C799B3FC5CE690F233F5C46D27A9208D" "E5EE8DDA802F915F2CF034E52B8076F41E85D1CE02E4F0A1588A4D3B3FEE343571A763D4B6A6709F7E01E21E2EB16624075541156C37B73F8D727346ABAD8D77B647718F1" "55B7792307527B2BA6579930018C56253560A858D0CD728E4E0C9DD5DC757416F807E177629CAE86C780BA5DD02C1D0740C29B8B995A07AEEBB0CC37C36CC10A425B2585E" "B88AEA26C4B79B3CF7779D3ADD96D7DC311FB1C0AC0D1A54512925D9EB4A59C66D6F7640B7608D70A21139B704701510E2831E9F77B17F532968CB53C086583FCBF0135AF" "17BE284C02BB789BC6D18D29BF142F80A5E509CCFD626D0D4CE429B8E7A371DE6594290E1E4A4E5DDA01948C413EFBC89D99D97BB51DD5EAB1D39A5E9381E5056FDFE4C5E" "BBE529A2F6F4F84CAD2C0B33A3CD7319A1591D817DA26C50D3A42802371190CFF84A0FAF922526CBA4950FB4005FB58A4D3B3FEE34357125999FF2C61E3F7C90C3597DC57" "C05BB", "token": "TICWq2R2F8fiidg6aUlfD5b95", "verifyCodeUuid": "e36fce5e-2a6c-4c74-af0b-18bfd0c7f60e", "keyIndex": "0001" }) print("parameters:", parameters) m = parameters.replace(' ', '').replace("'", '"') print('n:', m) n = quote(m) print('quote转码后的参数:', n) data = generateAES(randomPwd, n) print('AES加密后最终生成的data:', data) '''步骤二:生成参数rpd''' # rpd是AES密钥讲过RSA加密后生成的 rpd = generateRSA(ftpgs_key, randomPwd) print('RSA加密后生成的rpd:', rpd) '''步骤三:生成参数gsSign''' check_sign = "data=" + data + "&" + "rpd=" + rpd print("需要验签的参数:", check_sign) message = (check_sign).encode('utf-8') secret = ("AH6QfUTq").encode('utf-8') print("secret:", secret) signature = hmac.new(secret, message, digestmod=hashlib.sha256).digest() print('signature', signature) covert_check_sign = "".join(map(chr, signature)) # bytes转字符串,不用考虑编码 print("covert_check_sign", covert_check_sign) gsSign = toHex(covert_check_sign) # 调用Hex转换函数 print('gsSign:', gsSign) '''提交数据并解密''' data_login = {"data": data, "gsSign": gsSign, "rpd": rpd} print('最终参数:', data_login) url_login = '******' # print(url_login) req = requests.post(url_login, headers=headers_login, data=data_login, verify=False) print(req.json()) # responseContent = json.loads((req.json()['payload']))['responseContent'] # print(responseContent) print(req.headers) print(req.cookies) print('') print('') responseContent = ungenerateAES(randomPwd, responseContent) print(responseContent) responseContent = json.loads(responseContent) print(type(responseContent)) userNo = str(responseContent["userNo"]) print(userNo) cookie_login = req.cookies cookies_login = requests.utils.dict_from_cookiejar(cookie_login) return cookies_login, userNo
def get_flag(token): return PREFIX + hmac.new(FLAG_SECRET, token.encode(), 'sha256').hexdigest()[:FLAG_SALT_SIZE]
#print(hash.encode('hex')) #return hash #print("hash" + hash[::-1].encode('hex')) #return hash[::-1].encode('hex') #print sha256(sha256(x)) return sha256(sha256(x)) def TxHash(x): if type(x) is unicode: x = x.encode('utf-8') return getPoWHash(x) hash_encode = lambda x: x[::-1].encode('hex') hash_decode = lambda x: x.decode('hex')[::-1] hmac_sha_512 = lambda x, y: hmac.new(x, y, hashlib.sha512).digest() def is_new_seed(x, prefix=version.SEED_PREFIX): import mnemonic x = mnemonic.normalize_text(x) s = hmac_sha_512("Seed version", x.encode('utf8')).encode('hex') return s.startswith(prefix) def is_old_seed(seed): import old_mnemonic words = seed.strip().split() try: old_mnemonic.mn_decode(words) uses_electrum_words = True
seed_bytes = hashlib.pbkdf2_hmac("sha512", mnemonic, salt, 2048) seed = binascii.hexlify(seed_bytes) print("Seed: ", seed) # Ethereum uses Hierarchical Deterministic (HD) wallets as specified by BIP-32 # BIP-44 codifies the purpose of each depth level of hierarchical keys from the seed # BIP-44 => m / purpose / coin_type / account / change / address_index # most users of Ethereum uses addresses with a derivation path of m/44'/60'/0'/0/0 # m is just a convention, 44 is for the BIP-44 standard, 60 is coin_type for Ethereum network # 0 for account, 0 for change (mainly used only in Bitcoin) # 0 for address_index or index of account you are using # example: the 10th account is at path m/44'/60'/0'/0/9 # STEP 1: convert seed to a master key or root key # get HMAC-SHA512 and split resulting 64 bytes into left and right 32 byte sequences: I = hmac.new(b'Bitcoin seed', seed_bytes, hashlib.sha512).digest() print('HMAC-SHA512:', I) L, R = I[:32], I[32:] master_private_key = int.from_bytes(L, 'big') master_chain_code = R # note that the chain code mainly serves as entropy for subsequent child key derivations # 78 bytes are encoded to derive extended keys (a master root key, for example) VERSION_BYTES = { 'mainnet_public': binascii.unhexlify('0488b21e'), 'mainnet_private': binascii.unhexlify('0488ade4'), 'testnet_public': binascii.unhexlify('043587cf'), 'testnet_private': binascii.unhexlify('04358394'), } version_bytes = VERSION_BYTES['mainnet_private']
def __init__(self, name=None): self.bname = key_bytes(name) self.hmac = hmac.new(self.bname, digestmod='sha1')
class EC_KEY(object): def __init__(self, k): secret = string_to_number(k) self.pubkey = ecdsa.ecdsa.Public_key(generator_secp256k1, generator_secp256k1 * secret) self.privkey = ecdsa.ecdsa.Private_key(self.pubkey, secret) self.secret = secret def get_public_key(self, compressed=True): return point_to_ser(self.pubkey.point, compressed).encode('hex') def sign(self, msg_hash): private_key = MySigningKey.from_secret_exponent(self.secret, curve=SECP256k1) public_key = private_key.get_verifying_key() signature = private_key.sign_digest_deterministic( msg_hash, hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_string) assert public_key.verify_digest(signature, msg_hash, sigdecode=ecdsa.util.sigdecode_string) return signature def sign_message(self, message, is_compressed): signature = self.sign(Hash(msg_magic(message))) for i in range(4): sig = chr(27 + i + (4 if is_compressed else 0)) + signature try: self.verify_message(sig, message) return sig except Exception: continue else: raise Exception("error: cannot sign message") def verify_message(self, sig, message): h = Hash(msg_magic(message)) public_key, compressed = pubkey_from_signature(sig, h) # check public key if point_to_ser(public_key.pubkey.point, compressed) != point_to_ser( self.pubkey.point, compressed): raise Exception("Bad signature") # check message public_key.verify_digest(sig[1:], h, sigdecode=ecdsa.util.sigdecode_string) # ECIES encryption/decryption methods; AES-128-CBC with PKCS7 is used as the cipher; hmac-sha256 is used as the mac @classmethod def encrypt_message(self, message, pubkey): pk = ser_to_point(pubkey) if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()): raise Exception('invalid pubkey') ephemeral_exponent = number_to_string( ecdsa.util.randrange(pow(2, 256)), generator_secp256k1.order()) ephemeral = EC_KEY(ephemeral_exponent) ecdh_key = point_to_ser(pk * ephemeral.privkey.secret_multiplier) key = hashlib.sha512(ecdh_key).digest() iv, key_e, key_m = key[0:16], key[16:32], key[32:] ciphertext = aes_encrypt_with_iv(key_e, iv, message) ephemeral_pubkey = ephemeral.get_public_key( compressed=True).decode('hex') encrypted = 'BIE1' + ephemeral_pubkey + ciphertext mac = hmac.new(key_m, encrypted, hashlib.sha256).digest() return base64.b64encode(encrypted + mac) def decrypt_message(self, encrypted): encrypted = base64.b64decode(encrypted) if len(encrypted) < 85: raise Exception('invalid ciphertext: length') magic = encrypted[:4] ephemeral_pubkey = encrypted[4:37] ciphertext = encrypted[37:-32] mac = encrypted[-32:] if magic != 'BIE1': raise Exception('invalid ciphertext: invalid magic bytes') try: ephemeral_pubkey = ser_to_point(ephemeral_pubkey) except AssertionError, e: raise Exception('invalid ciphertext: invalid ephemeral pubkey') if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, ephemeral_pubkey.x(), ephemeral_pubkey.y()): raise Exception('invalid ciphertext: invalid ephemeral pubkey') ecdh_key = point_to_ser(ephemeral_pubkey * self.privkey.secret_multiplier) key = hashlib.sha512(ecdh_key).digest() iv, key_e, key_m = key[0:16], key[16:32], key[32:] if mac != hmac.new(key_m, encrypted[:-32], hashlib.sha256).digest(): raise InvalidPassword() return aes_decrypt_with_iv(key_e, iv, ciphertext)
def hmac(self, key, msg): return hmac.new(key, msg, digestmod=self.hashfunc).digest()
def hmacSha256(key, text): return hmac.new(key, text, sha256_module).digest()
def _generate_signature(self, string_to_sign, date_stamp): signing_key = self._get_signature_key(date_stamp) signature = hmac.new(signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest() return signature
def get_signature(encoded_payload, secret_key): signature = hmac.new(str(secret_key).upper(), str(encoded_payload), hashlib.sha512); return signature.hexdigest()
def hash_str(s): return hmac.new(secret_key, s).hexdigest()
def _sign(cls, key, message): return hmac.new(key, message.encode('utf-8'), hashlib.sha256).digest()
def _do_api_request(self, url, method="GET", body=None, headers=None): headers = headers or {} if self.signature and self.api.client_ips != None and self.api.client_secret != None: secret = self.api.client_secret ips = self.api.client_ips signature = hmac.new(secret, ips, sha256).hexdigest() headers['X-Insta-Forwarded-For'] = '|'.join([ips, signature]) response, content = OAuth2Request(self.api).make_request( url, method=method, body=body, headers=headers) if response['status'] == '503' or response['status'] == '429': raise InstagramAPIError( response['status'], "Rate limited", "Your client is making too many request per second") try: content_obj = simplejson.loads(content) except ValueError: raise InstagramClientError( 'Unable to parse response, not valid JSON.', status_code=response['status']) # Handle OAuthRateLimitExceeded from Instagram's Nginx which uses different format to documented api responses if not content_obj.has_key('meta'): if content_obj.get('code') == 420 or content_obj.get( 'code') == 429: error_message = content_obj.get( 'error_message' ) or "Your client is making too many request per second" raise InstagramAPIError(content_obj.get('code'), "Rate limited", error_message) raise InstagramAPIError(content_obj.has_key('code'), content_obj.has_key('error_type'), content_obj.has_key('error_message')) api_responses = [] status_code = content_obj['meta']['code'] self.api.x_ratelimit_remaining = response.get( "x-ratelimit-remaining", None) self.api.x_ratelimit = response.get("x-ratelimit-limit", None) if status_code == 200: if not self.objectify_response: return content_obj, None if self.response_type == 'list': for entry in content_obj['data']: if self.return_json: api_responses.append(entry) else: obj = self.root_class.object_from_dictionary(entry) api_responses.append(obj) elif self.response_type == 'entry': data = content_obj['data'] if self.return_json: api_responses = data else: api_responses = self.root_class.object_from_dictionary( data) elif self.response_type == 'empty': pass return api_responses, self._build_pagination_info(content_obj) else: raise InstagramAPIError(status_code, content_obj['meta']['error_type'], content_obj['meta']['error_message'])
def password_to_hmac(salt, password): m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), 'SHA256') return m.hexdigest()
""" import base64 import hashlib import hmac try: import json except ImportError: import simplejson as json __all__ = ['encode', 'decode', 'DecodeError'] class DecodeError(Exception): pass signing_methods = { 'HS256': lambda msg, key: hmac.new(key, msg, hashlib.sha256).digest(), 'HS384': lambda msg, key: hmac.new(key, msg, hashlib.sha384).digest(), 'HS512': lambda msg, key: hmac.new(key, msg, hashlib.sha512).digest(), } def base64url_decode(input): rem = len(input) % 4 if rem > 0: input += '=' * (4 - rem) return base64.urlsafe_b64decode(input) def base64url_encode(input): return base64.urlsafe_b64encode(input).replace('=', '') def header(jwt): header_segment = jwt.split('.', 1)[0]
def js_config(extra_config=None): logged = c.user_is_loggedin and c.user.name gold = bool(logged and c.user.gold) controller_name = request.environ['pylons.routes_dict']['controller'] action_name = request.environ['pylons.routes_dict']['action'] mac = hmac.new(g.secrets["action_name"], controller_name + '.' + action_name, hashlib.sha1) verification = mac.hexdigest() config = { # is the user logged in? "logged": logged, # the subreddit's name (for posts) "post_site": c.site.name if not c.default_sr else "", # the user's voting hash "modhash": c.modhash or False, # the current rendering style "renderstyle": c.render_style, # they're welcome to try to override this in the DOM because we just # disable the features server-side if applicable 'store_visits': gold and c.user.pref_store_visits, # current domain "cur_domain": get_domain(cname=c.frameless_cname, subreddit=False, no_www=True), # where do ajax requests go? "ajax_domain": get_domain(cname=c.authorized_cname, subreddit=False), "extension": c.extension, "https_endpoint": is_subdomain(request.host, g.domain) and g.https_endpoint, # does the client only want to communicate over HTTPS? "https_forced": c.user.https_forced, # debugging? "debug": g.debug, "send_logs": g.live_config["frontend_logging"], "server_time": math.floor(time.time()), "status_msg": { "fetching": _("fetching title..."), "submitting": _("submitting..."), "loading": _("loading...") }, "is_fake": isinstance(c.site, FakeSubreddit), "fetch_trackers_url": g.fetch_trackers_url, "adtracker_url": g.adtracker_url, "clicktracker_url": g.clicktracker_url, "uitracker_url": g.uitracker_url, "static_root": static(''), "over_18": bool(c.over18), "new_window": bool(c.user.pref_newwindow), "vote_hash": c.vote_hash, "gold": gold, "has_subscribed": logged and c.user.has_subscribed, "pageInfo": { "verification": verification, "actionName": controller_name + '.' + action_name, }, } if g.uncompressedJS: config["uncompressedJS"] = True if extra_config: config.update(extra_config) hooks.get_hook("js_config").call(config=config) return config
def hash_str(s): return hmac.new(SECRET, s).hexdigest() return hashlib.md5(s).hexdigest()
def hash_str(s, secret): """ Return hash of string """ return hmac.new(secret, s).hexdigest()
def sign_data(key, data): """Sign the data using the defined function and the derived key.""" mac = hmac.new(key, data, HASH_FUNCTION).digest() return base64.b64encode(mac)
def hash_fn(x): return hmac.new(hash_key.encode('utf-8'), x.encode('utf-8')).digest()
def __compute_hmac(base_key, sid, text): """Computes the signature for text given base_key and sid.""" key = base_key + sid return b64encode(hmac.new(key, text, hashlib.sha256).digest())
def connect( self, request, response, db=None, tablename='web2py_session', masterapp=None, migrate=True, separate = None, check_client=False, cookie_key=None, ): """ separate can be separate=lambda(session_name): session_name[-2:] and it is used to determine a session prefix. separate can be True and it is set to session_name[-2:] """ if separate == True: separate = lambda session_name: session_name[-2:] self._unlock(response) if not masterapp: masterapp = request.application response.session_id_name = 'session_id_%s' % masterapp.lower() # Load session data from cookie cookies = request.cookies if cookie_key: response.session_cookie_key = cookie_key response.session_cookie_key2 = hashlib.md5(cookie_key).digest() cookie_name = masterapp.lower()+'_session_data' response.session_cookie_name = cookie_name if cookie_name in cookies: cookie_value = cookies[cookie_name].value cookie_parts = cookie_value.split(":") enc = cookie_parts[2] cipher = AES.new(cookie_key) decrypted = cipher.decrypt(base64.b64decode(enc)).rstrip('{') check = hmac.new(response.session_cookie_key2,enc).hexdigest() if cookie_parts[0] == check: session_data = cPickle.loads(decrypted) self.update(session_data) else: return if not db: if global_settings.db_sessions is True \ or masterapp in global_settings.db_sessions: return response.session_new = False client = request.client and request.client.replace(':', '.') if response.session_id_name in cookies: response.session_id = \ cookies[response.session_id_name].value if regex_session_id.match(response.session_id): response.session_filename = \ os.path.join(up(request.folder), masterapp, 'sessions', response.session_id) else: response.session_id = None if response.session_id: try: response.session_file = \ open(response.session_filename, 'rb+') try: portalocker.lock(response.session_file, portalocker.LOCK_EX) response.session_locked = True self.update(cPickle.load(response.session_file)) response.session_file.seek(0) oc = response.session_filename.split('/')[-1]\ .split('-')[0] if check_client and client!=oc: raise Exception, "cookie attack" finally: pass #This causes admin login to break. Must find out why. #self._close(response) except: response.session_id = None if not response.session_id: uuid = web2py_uuid() response.session_id = '%s-%s' % (client, uuid) if separate: prefix = separate(response.session_id) response.session_id = '%s/%s' % \ (prefix,response.session_id) response.session_filename = \ os.path.join(up(request.folder), masterapp, 'sessions', response.session_id) response.session_new = True else: if global_settings.db_sessions is not True: global_settings.db_sessions.add(masterapp) response.session_db = True if response.session_file: self._close(response) if settings.global_settings.web2py_runtime_gae: # in principle this could work without GAE request.tickets_db = db if masterapp == request.application: table_migrate = migrate else: table_migrate = False tname = tablename + '_' + masterapp table = db.get(tname, None) Field = db.Field if table is None: db.define_table( tname, Field('locked', 'boolean', default=False), Field('client_ip', length=64), Field('created_datetime', 'datetime', default=request.now), Field('modified_datetime', 'datetime'), Field('unique_key', length=64), Field('session_data', 'blob'), migrate=table_migrate, ) table = db[tname] # to allow for lazy table try: # Get session data out of the database # Key comes from the cookie key = cookies[response.session_id_name].value (record_id, unique_key) = key.split(':') if record_id == '0': raise Exception, 'record_id == 0' # Select from database rows = db(table.id == record_id).select() # Make sure the session data exists in the database if len(rows) == 0 or rows[0].unique_key != unique_key: raise Exception, 'No record' # rows[0].update_record(locked=True) # Unpickle the data session_data = cPickle.loads(rows[0].session_data) self.update(session_data) except Exception: record_id = None unique_key = web2py_uuid() session_data = {} response._dbtable_and_field = \ (response.session_id_name, table, record_id, unique_key) response.session_id = '%s:%s' % (record_id, unique_key) rcookies = response.cookies rcookies[response.session_id_name] = response.session_id rcookies[response.session_id_name]['path'] = '/' self.__hash = hashlib.md5(str(self)).digest() if self.flash: (response.flash, self.flash) = (self.flash, None)