#!/usr/bin/env python # encoding: utf-8 # # SPDX-License-Identifier: LGPL-2.1-or-later from __future__ import unicode_literals, absolute_import, division import hmac import hashlib import time import random import string from urllib.parse import urlparse, urlsplit, parse_qs, urlencode, quote, unquote from .b64 import encode_base64, decode_base64 from .log import LOG def generate_nonce(length=24): characters = string.ascii_lowercase + string.digits nonce = ''.join(random.choice(characters) for _ in range(length)) return encode_base64(nonce) def create_signature(method, url, token, scheme): consumer_key = 'web_1.0.0' consumer_secret = 'Rk1Qc2RaREJ0M1h1MkUwRWtJRmlxWGtpOVpOZFlGN3I=' nonce = generate_nonce() #print('nonce', nonce) timestamp = int(time.time()) parsed_url = urlsplit(url) path = parsed_url.netloc + parsed_url.path query = parse_qs(parsed_url.query, keep_blank_values=True) options = { scheme: token, 'consumer_key': consumer_key, 'nonce': nonce, 'signature_method': 'HMAC-SHA1', 'version': '1.0', 'timestamp': timestamp} for k, v in query.items(): options[k] = quote(v[0]) query_string = "&".join("{}={}".format(key, value) for key, value in sorted(options.items())) #print(query_string) text = '{}&{}&{}'.format(method.upper(), quote(path, safe=''), quote(query_string, safe='')) #print(text) key = decode_base64(consumer_secret.encode('utf-8')).encode('utf-8') hashed = hmac.new(key, text.encode('utf-8'), hashlib.sha1).digest() signature = encode_base64(hashed) res = 'consumer_key="{}",nonce="{}",signature_method="HMAC-SHA1",signature="{}",timestamp="{}",version="1.0"'.format(consumer_key, nonce, signature, timestamp) return encode_base64(res) def get_auth(method, url, token, scheme='Bearer'): signature = create_signature(method, url, token, scheme) return 'OPPlus {}={},Signature={}'.format(scheme, token, signature)