Exemplo n.º 1
0
def token_seachange(path, argument, ip):
    passed = False
    uri = path  # Just for warnings in the exception handler

    # Rebuild query string in correct order...
    # NOTE: Use more local variables for debugging purposes.

    try:
        # Check for address
        if config.seachange["ip_restrict"] and argument["a"] != ip:
            return False

        # Check for expired date - SeaChange uses UTC
        if config.seachange["expire_date_restrict"]:
            if config.token_types["seachange"] == "SHA1":
                expire_date = calendar.timegm(argument["e"])
            else:
                end = str(argument["e"])
                year = end[:4]
                month = end[4:2]
                day = end[6:2]
                hour = end[8:2]
                minute = end[10:2]
                second = end[12:]
                expire_date = datetime.datetime(year, month, day, hour, minute, second)

            if datetime.datetime.utcnow() > expire_date:
                return False

        uri = str("%s?i=%s&k=%s&e=%s&a=%s" % (path, argument["i"], argument["k"], argument["e"], argument["a"])).lower()

        # byte_string = uri.encode('utf-8')
        # byte_string = bytearray(uri, 'utf-8')
        key = config.keys_seachange[argument["k"]]

        if config.token_types["seachange"] == "MD5":
            token = hmac(key.decode("hex"), uri, md5)
        else:
            token = hmac(key.decode("hex"), uri, sha1)

        hex_value = token.hexdigest()

        if hex_value == argument["h"]:
            passed = True

        if config.logging:
            if passed:
                return_code = config.http_response_codes["found"]
                msg = "%s = %s" % (hex_value, argument["h"])
            else:
                return_code = config.http_response_codes["forbidden"]
                msg = "%s != %s" % (hex_value, argument["h"])
            log('%s - - "TOKEN(SC) %s" %s %s "%s" "%s" "-"' % (ip, uri, return_code, 0, msg, argument))

    except BaseException, e:
        log(
            '%s - - "GET %s" %s %s "%s" "%s" "-"' % (ip, uri, config.http_response_codes["forbidden"], 0, e, argument),
            level="WARNING",
            log_type="ERROR",
        )
Exemplo n.º 2
0
def create_token(access_key, secret_key):
    t = str(time.time())

    if sys.version > "3":
        token = base64.encodebytes(hmac(
            bytearray("%s,%s,%s" % (access_key, t, secret_key), "utf-8"), digestmod=sha1).digest())[:-1]
    else:
        token = base64.encodestring(hmac("%s,%s,%s" % (access_key, t, secret_key), digestmod=sha1).digest())[:-1]

    return t, token
Exemplo n.º 3
0
    def serialize(self, expires=None):
        """Serialize the secure cookie into a string.

        If expires is provided, the session will be automatically invalidated
        after expiration when you unseralize it. This provides better
        protection against session cookie theft.

        :param expires: an optional expiration date for the cookie (a
                        :class:`datetime.datetime` object)
        """
        if self.secret_key is None:
            raise RuntimeError('no secret key defined')
        if expires:
            self['_expires'] = _date_to_unix(expires)
        result = []
        mac = hmac(self.secret_key, None, self.hash_method)
        for key, value in sorted(self.items()):
            result.append('%s=%s' % (
                url_quote_plus(key),
                self.quote(value)
            ))
            mac.update('|' + result[-1])
        return '%s?%s' % (
            mac.digest().encode('base64').strip(),
            '&'.join(result)
        )
Exemplo n.º 4
0
  def __init__ (self, confFile):
    setCatch(5)
    confFile = path.expanduser(confFile)
    self.file = confFile
    with open(confFile) as handle:
      self.options = load(handle)
    
    if not 'secret' in self.options:
      raise Exception
    if 'ratelimit' in self.options:
      self.options['ratelimit'].setdefault('limit', 3)
      self.options['ratelimit'].setdefault('window', 0)
      self.options['ratelimit'].setdefault('counter', 0)
    self.options.setdefault('window', 1)
    self.options.setdefault('timer', 30)

    self.time = int(time() /30)
    Secret = b32decode(self.options['secret'].encode('ascii'))
    Drift = int(self.options['window'])
    self.keys = []

    for SkewedTime in range(self.time-Drift,self.time+Drift+1):
      ByteTime = pack(">q", SkewedTime)
      Hash = hmac(Secret, ByteTime, sha1).digest()
      Offset = Hash[-1] & 0x0F
      ShortHash = Hash[Offset:Offset+4]
      Code = unpack('>L', ShortHash)[0]
      Code &= 0x7FFFFFFF
      Code %= 1000000
      Code = "%06d" % Code
      self.keys.append(Code)
Exemplo n.º 5
0
def _check_request(request_url, method = 'GET'):
    try:
        if isinstance(request_url, unicode):
            request_url = request_url.encode('utf8')
    
        p = urlparse.urlparse(request_url)
        url = p.scheme + '://' + p.netloc + p.path
        params = {key: value[0] for key, value in urlparse.parse_qs(p.query).items()}
        
        signature = params['oauth_signature']
        del params['oauth_signature']
        user_name = params['token']
        secret = userinfo.user_info(user_name)['password']
        customer_secret = 'lava_potion'

        # Join all of the params together.
        params_str = "&".join(["%s=%s" % (encode(k), encode(params[k]))
                            for k in sorted(params)])

        # Join the entire message together per the OAuth specification.
        message = "&".join([encode(method), encode(url), encode(params_str)])

        # Create a HMAC-SHA1 signature of the message.
        key = "%s&%s" % (secret, '') # Note compulsory "&".
        key = key.encode('utf-8')
        
        if signature == hmac(key, message, sha1).digest().encode("base64").strip():
            return True
        else:
            return False
    
    except:
        return False
    def get_signed_body(self, __url, __token=None, __meth="GET", **extra_params):

        service_info = self.service_info

        kwargs = {
            "oauth_consumer_key": service_info["consumer_key"],
            "oauth_signature_method": "HMAC-SHA1",
            "oauth_version": "1.0",
            "oauth_timestamp": int(time()),
            "oauth_nonce": getrandbits(64),
        }

        kwargs.update(extra_params)

        if self.service_key is None:
            self.service_key = get_service_key(self.service)

        if __token is not None:
            kwargs["oauth_token"] = __token.oauth_token
            key = self.service_key + encode(__token.oauth_token_secret)
        else:
            key = self.service_key

        message = "&".join(
            map(
                encode,
                [__meth.upper(), __url, "&".join("%s=%s" % (encode(k), encode(kwargs[k])) for k in sorted(kwargs))],
            )
        )

        kwargs["oauth_signature"] = hmac(key, message, sha1).digest().encode("base64")[:-1]

        return urlencode(dict([k, v.encode("utf-8") if isinstance(v, unicode) else v] for k, v in kwargs.items()))
Exemplo n.º 7
0
 def _form_signed_params(self, method, url, token='', secret='', additional_params={}):
     ''' Form Signed Params
     '''
     # Add OAuth parameters.
     params = {
         'oauth_consumer_key': self.consumer_key,
         'oauth_signature_method': 'HMAC-SHA1',
         'oauth_timestamp': str(int(time.time())),
         'oauth_nonce': str(random.getrandbits(64)),
         'oauth_version': '1.0'
     }
     params.update(additional_params)
     if token:    params['oauth_token'] = token
     else:         params['oauth_callback'] = self.callback_url
     
     # Create a message of the params.
     params_string = self._normalize_parameters(params)
     message = ('&'.join([ self._quote(method), self._quote(url), self._quote(params_string) ])).encode('utf-8')
     
     # Create a HMAC-SHA1 signature of the message.
     key = ('%s&%s' % (self.consumer_secret, secret)).encode('utf-8')
     signature = hmac(key, message, hashlib.sha1)
     params['oauth_signature'] = b64encode(signature.digest()).strip()
     
     return params
    def serialize(self, expires=None):
        """Serialize the secure cookie into a string.

        If expires is provided, the session will be automatically invalidated
        after expiration when you unseralize it. This provides better
        protection against session cookie theft.
        """
        if self.secret_key is None:
            raise RuntimeError('no secret key defined')
        if expires:
            if isinstance(expires, datetime):
                expires = expires.utctimetuple()
            elif isinstance(expires, (int, long, float)):
                expires = gmtime(expires)
            self['_expires'] = int(mktime(expires))
        result = []
        mac = hmac(self.secret_key, None, self.hash_method)
        for key, value in self.iteritems():
            result.append('%s=%s' % (
                url_quote_plus(key),
                pickle_quote(value)
            ))
            mac.update('|' + result[-1])
        return '%s?%s' % (
            mac.digest().encode('base64').strip(),
            '&'.join(result)
        )
Exemplo n.º 9
0
 def _token(self, plate):
     """Generates SHA1 token as HEX based on specified and secret key."""
     plate_and_secret = '%s%s' % (plate, SECRET)
     plate_and_secret = bytes(plate_and_secret.encode('utf-8'))
     plate = plate.encode('utf-8')
     hmac_key = hmac(plate_and_secret, plate, sha1)
     return hmac_key.hexdigest()
Exemplo n.º 10
0
    def get_signed_body(self, __url, __token=None, __meth='GET',**extra_params):

        service_info = self.service_info

        kwargs = {
            'oauth_consumer_key': service_info['consumer_key'],
            'oauth_signature_method': 'HMAC-SHA1',
            'oauth_version': '1.0',
            'oauth_timestamp': int(time()),
            'oauth_nonce': getrandbits(64),
            }

        kwargs.update(extra_params)

        if self.service_key is None:
            self.service_key = get_service_key(self.service)

        if __token is not None:
            kwargs['oauth_token'] = __token.oauth_token
            key = self.service_key + encode(__token.oauth_token_secret)
        else:
            key = self.service_key

        message = '&'.join(map(encode, [
            __meth.upper(), __url, '&'.join(
                '%s=%s' % (encode(k), encode(kwargs[k])) for k in sorted(kwargs)
                )
            ]))

        kwargs['oauth_signature'] = hmac(
            key, message, sha1
            ).digest().encode('base64')[:-1]

        return urlencode(kwargs)
Exemplo n.º 11
0
Arquivo: totp.py Projeto: akerl/totp
    def __init__(self, confFile):
        setCatch(5)
        confFile = path.expanduser(confFile)
        self.file = confFile
        with open(confFile) as handle:
            self.options = load(handle)

        if not "secret" in self.options:
            raise Exception
        if "ratelimit" in self.options:
            self.options["ratelimit"].setdefault("limit", 3)
            self.options["ratelimit"].setdefault("window", 0)
            self.options["ratelimit"].setdefault("counter", 0)
        self.options.setdefault("window", 1)
        self.options.setdefault("timer", 30)

        self.time = int(time() / 30)
        Secret = b32decode(self.options["secret"].encode("ascii"))
        Drift = int(self.options["window"])
        self.keys = []

        for SkewedTime in range(self.time - Drift, self.time + Drift + 1):
            ByteTime = pack(">q", SkewedTime)
            Hash = hmac(Secret, ByteTime, sha1).digest()
            Offset = Hash[-1] & 0x0F
            ShortHash = Hash[Offset : Offset + 4]
            Code = unpack(">L", ShortHash)[0]
            Code &= 0x7FFFFFFF
            Code %= 1000000
            Code = "{0:06d}".format(Code)
            self.keys.append(Code)
Exemplo n.º 12
0
def send_beaker_encrypt(validate_key, add, payload, encrypt_key):
    from beaker import crypto #yes we need it, will port it when we have time
    nonce = '12345678' #anything 8 bytes
    encrypt_key = crypto.generateCryptoKeys(encrypt_key, validate_key + nonce, 1)
    data = nonce + b64(crypto.aesEncrypt(payload, encrypt_key))
    mac = hmac(validate_key, data.encode('UTF-8'), hashlib.sha1).hexdigest()
    s = mac + data
    print requests.get(add, cookies={'beaker.session.id':s})
Exemplo n.º 13
0
 def get_xsrf_token(self):
     """
     Return an opaque cross-site request forgery (XSRF) token for use
     in forms.
     """
     now = str(time())
     digest = hmac(self.secret_key, now, sha256).hexdigest()
     return now + ":" + digest
Exemplo n.º 14
0
 def create_aes(self, self_key):
     if isinstance(self_key, unicode):
         self_key = self_key.encode('ascii')
     if isinstance(self.username, unicode):
         self.username = self.username.encode('ascii')
     data = hmac(
         self.username, self_key, sha512
         ).digest()
     return AES.new(data[:32], AES.MODE_CBC,data[32:32])
Exemplo n.º 15
0
def hello():
    key = 'Valar Morghulis'
    file_name = request.args.get('file')
    sig = request.args.get('signature')

    if bad_compare(hmac.hmac(key, file_name), sig):
        return 'true'
    else:
        return 'false'
 def getAccountString(self):
     methodstr = "method=getForwardsAccountInfo&params="
     tonce = '%d'%(time.time() * 1000000)
     params = "tonce=" + tonce + "&accesskey=" + self.accesskey + "&requestmethod=post&id=1&" + methodstr
     hash = hmac(self.secretkey, params, hashlib.sha1).hexdigest()
     userpass = self.accesskey + ":" + hash;
     userpass = base64.b64encode(userpass)
     basicAuth = "%s:Basic %s"%(tonce,userpass)
     return basicAuth
Exemplo n.º 17
0
def serialize_dictionary(dictionary, secret_key=settings.SERIALIZATION_SECRET_KEY, expires=None):
    secret_key = str(secret_key)    
    if expires:
        dictionary['_expires'] = _date_to_unix(expires)        
    mac = hmac(secret_key, None, sha1)
    result = []
    for key, value in dictionary.iteritems():
        result.append('%s=%s' % (url_quote_plus(key), _quote(value)))
        mac.update('|' + result[-1])        
    return '%s?%s' % (mac.digest().encode('base64').strip(),'&'.join(result))
Exemplo n.º 18
0
def main():
  key = 'ecbefbf6b17e47ecb9035107866380'
  grant_type = 'password'
  client_id = '8d5227e0aaaa4797a763ac64e0c3b8'
  source = 'com.zhihu.android'
  timestamp = '1425481982'
  message = ''.join([grant_type, client_id, source, timestamp])
  
  signature = hmac(key, message, sha1).hexdigest()
  
  print signature
Exemplo n.º 19
0
def get_sign(method, url, params, key):
    ar = [method, 
          url, 
          '&'.join('%s=%s' % (quote(k, ''), 
                              quote(params[k], '')) for k in sorted(params))]
    ar = map((lambda x: quote(x, '')), ar)
    message = '&'.join(ar)
    return hmac(key, 
                message, 
                sha1
                ).digest().encode('base64')[:-1]
Exemplo n.º 20
0
    def unserialize(cls, string, secret_key):
        """Load the secure cookie from a serialized string.

        :param string: the cookie value to unserialize.
        :param secret_key: the secret key used to serialize the cookie.
        :return: a new :class:`SecureCookie`.
        """
        # explicitly convert it into a bytestring because python 2.6
        # no longer performs an implicit string conversion on hmac
        secret_key = str(secret_key)
        if isinstance(string, unicode):
            string = string.encode('utf-8', 'replace')
        try:
            base64_hash, data = string.split('?', 1)
        except (ValueError, IndexError):
            items = ()
        else:
            items = {}
            mac = hmac(secret_key, None, cls.hash_method)
            for item in data.split('&'):
                mac.update('|' + item)
                if not '=' in item:
                    items = None
                    break
                key, value = item.split('=', 1)
                # try to make the key a string
                key = url_unquote_plus(key)
                try:
                    key = str(key)
                except UnicodeError:
                    pass
                items[key] = value

            # no parsing error and the mac looks okay, we can now
            # sercurely unpickle our cookie.
            try:
                client_hash = base64_hash.decode('base64')
            except Exception:
                items = client_hash = None
            if items is not None and safe_str_cmp(client_hash, mac.digest()):
                try:
                    for key, value in items.iteritems():
                        items[key] = cls.unquote(value)
                except UnquoteError:
                    items = ()
                else:
                    if '_expires' in items:
                        if time() > items['_expires']:
                            items = ()
                        else:
                            del items['_expires']
            else:
                items = ()
        return cls(items, secret_key, False)
Exemplo n.º 21
0
    def unserialize(cls, string, secret_key):
        """Load the secure cookie from a serialized string.

        :param string: the cookie value to unserialize.
        :param secret_key: the secret key used to serialize the cookie.
        :return: a new :class:`SecureCookie`.
        """
        if isinstance(string, text_type):
            string = string.encode('utf-8', 'replace')
        if isinstance(secret_key, text_type):
            secret_key = secret_key.encode('utf-8', 'replace')
        try:
            base64_hash, data = string.split(b'?', 1)
        except (ValueError, IndexError):
            items = ()
        else:
            items = {}
            mac = hmac(secret_key, None, cls.hash_method)
            for item in data.split(b'&'):
                mac.update(b'|' + item)
                if not b'=' in item:
                    items = None
                    break
                key, value = item.split(b'=', 1)
                # try to make the key a string
                key = url_unquote_plus(key.decode('ascii'))
                try:
                    key = to_native(key)
                except UnicodeError:
                    pass
                items[key] = value

            # no parsing error and the mac looks okay, we can now
            # sercurely unpickle our cookie.
            try:
                client_hash = base64.b64decode(base64_hash)
            except TypeError:
                items = client_hash = None
            if items is not None and safe_str_cmp(client_hash, mac.digest()):
                try:
                    for key, value in iteritems(items):
                        items[key] = cls.unquote(value)
                except UnquoteError:
                    items = ()
                else:
                    if '_expires' in items:
                        if time() > items['_expires']:
                            items = ()
                        else:
                            del items['_expires']
            else:
                items = ()
        return cls(items, secret_key, False)
Exemplo n.º 22
0
    def unserialize(cls, string, secret_key):
        """Load the secure cookie from a serialized string.

        :param string: the cookie value to unserialize.
        :param secret_key: the secret key used to serialize the cookie.
        :return: a new :class:`SecureCookie`.
        """
        if isinstance(string, unicode):
            string = string.encode("utf-8", "replace")
        if isinstance(secret_key, unicode):
            secret_key = secret_key.encode("utf-8", "replace")
        try:
            base64_hash, data = string.split("?", 1)
        except (ValueError, IndexError):
            items = ()
        else:
            items = {}
            mac = hmac(secret_key, None, cls.hash_method)
            for item in data.split("&"):
                mac.update("|" + item)
                if not "=" in item:
                    items = None
                    break
                key, value = item.split("=", 1)
                # try to make the key a string
                key = url_unquote_plus(key)
                try:
                    key = str(key)
                except UnicodeError:
                    pass
                items[key] = value

            # no parsing error and the mac looks okay, we can now
            # sercurely unpickle our cookie.
            try:
                client_hash = base64_hash.decode("base64")
            except Exception:
                items = client_hash = None
            if items is not None and safe_str_cmp(client_hash, mac.digest()):
                try:
                    for key, value in items.iteritems():
                        items[key] = cls.unquote(value)
                except UnquoteError:
                    items = ()
                else:
                    if "_expires" in items:
                        if time() > items["_expires"]:
                            items = ()
                        else:
                            del items["_expires"]
            else:
                items = ()
        return cls(items, secret_key, False)
Exemplo n.º 23
0
    def serialize(self, expires = None):
        if self.secret_key is None:
            raise RuntimeError('no secret key defined')
        if expires:
            self['_expires'] = _date_to_unix(expires)
        result = []
        mac = hmac(self.secret_key, None, self.hash_method)
        for key, value in sorted(self.items()):
            result.append('%s=%s' % (url_quote_plus(key), self.quote(value)))
            mac.update('|' + result[-1])

        return '%s?%s' % (mac.digest().encode('base64').strip(), '&'.join(result))
    def __init__(self, AWSAccessKeyId, SigningKey):
        self.today = datetime.date.today()
        self.xml_blob = ""

        # get the datetime directly from route53 to prevent clock issues
        self._datetime = self.get_date_time()

        # now generate the correct autentication from the access keys using HMAC SHA1
        self._accessKey = AWSAccessKeyId
        self._signingKey = SigningKey
        sig = hmac(self._signingKey, self._datetime, sha1).digest().encode("base64")
        self._auth_header = "AWS3-HTTPS AWSAccessKeyId=" + AWSAccessKeyId + ",Algorithm=HmacSHA1,Signature=" + sig
Exemplo n.º 25
0
    def prepare_request(
        self, url, token="", secret="", additional_params=None, method=urlfetch.GET, t=None, nonce=None
    ):
        """Prepare Request.

    Prepares an authenticated request to any OAuth protected resource.

    Returns the payload of the request.
    """

        def encode(text):
            return urlquote(str(text), "~")

        params = {
            "oauth_consumer_key": self.consumer_key,
            "oauth_signature_method": "HMAC-SHA1",
            "oauth_timestamp": t if t else str(int(time())),
            "oauth_nonce": nonce if nonce else str(getrandbits(64)),
            "oauth_version": "1.0",
        }

        if token:
            params["oauth_token"] = token
        elif self.callback_url:
            params["oauth_callback"] = self.callback_url

        if additional_params:
            params.update(additional_params)

        for k, v in params.items():
            if isinstance(v, unicode):
                params[k] = v.encode("utf8")

        # Join all of the params together.
        params_str = "&".join(["%s=%s" % (encode(k), encode(params[k])) for k in sorted(params)])

        # Join the entire message together per the OAuth specification.
        if method == urlfetch.GET:
            meth = "GET"
        elif method == urlfetch.PUT:
            meth = "PUT"
        else:
            meth = "POST"
        message = "&".join([meth, encode(url), encode(params_str)])

        # Create a HMAC-SHA1 signature of the message.
        key = "%s&%s" % (self.consumer_secret, secret)  # Note compulsory "&".
        signature = hmac(key, message, sha1)
        digest_base64 = signature.digest().encode("base64").strip()
        params["oauth_signature"] = digest_base64

        # Construct the request payload and return it
        return urlencode(params)
Exemplo n.º 26
0
  def _generate_signature(self, method, url, oauth_params, payload, secret):
    """Generates a HMAC-SHA1 signature for the request."""
    # Join all of the params together.
    combined = oauth_params.copy()
    combined.update(payload)
    params_str = "&".join(["%s=%s" % (self._encode(k), self._encode(combined[k]))
                           for k in sorted(combined)])
    # Join the entire message together per the OAuth specification.
    message = "&".join([self._encode(item) for item in (method, url, params_str)])

    # Create a HMAC-SHA1 signature of the message.
    key = "%s&%s" % (self.consumer_secret, secret) # Note compulsory "&".
    signature = hmac(key, message, sha1)
    return signature.digest().encode("base64").strip()
Exemplo n.º 27
0
  def prepare_request(self, url, token='', secret='', additional_params=None,
                      method=urlfetch.GET, t=None, nonce=None):
    '''Prepare Request.

    Prepares an authenticated request to any OAuth protected resource.

    Returns the payload of the request.
    '''

    def encode(text):
      return urlquote(str(text), '~')

    params = {
      'oauth_consumer_key': self.consumer_key,
      'oauth_signature_method': 'HMAC-SHA1',
      'oauth_timestamp': t if t else str(int(time())),
      'oauth_nonce': nonce if nonce else str(getrandbits(64)),
      'oauth_version': '1.0'
    }

    if token:
      params['oauth_token'] = token
    elif self.callback_url:
      params['oauth_callback'] = self.callback_url

    if additional_params:
        params.update(additional_params)

    for k,v in params.items():
        if isinstance(v, unicode):
            params[k] = v.encode('utf8')

    # Join all of the params together.
    params_str = '&'.join(['%s=%s' % (encode(k), encode(params[k]))
                           for k in sorted(params)])

    # Join the entire message together per the OAuth specification.
    message = '&'.join(['GET' if method == urlfetch.GET else 'POST',
                       encode(url), encode(params_str)])

    # Create a HMAC-SHA1 signature of the message.
    key = '%s&%s' % (self.consumer_secret, secret) # Note compulsory '&'.
    signature = hmac(key, message, sha1)
    digest_base64 = signature.digest().encode('base64').strip()
    params['oauth_signature'] = digest_base64

    # Construct the request payload and return it
    return urlencode(params)
Exemplo n.º 28
0
Arquivo: sign.py Projeto: jmzc/sign
def _sign(secret,query):
        try:
		parameters = parse_qs(query,False,True)
                keys = sorted(parameters)
                result = ()
                for key in keys:
                        result = result + ((key, parameters[key][0]),)
                url = urlencode(result)
                print "Signing->" + secret + url + '&'
                mac = hmac(secret, secret + url + '&', sha1).digest().encode('base64')[:-1]

                return mac; 


        except ValueError:
                return 'Error'
Exemplo n.º 29
0
def send(message, sock: socket):
    global aes_key, hmac_key
    ciphertext = aes.cfb_encrypt(message.encode("utf-8"), aes_key)
    mac = hmac.hmac(ciphertext, hmac_key)
    payload = mac + ciphertext
    sock.sendall(payload)
Exemplo n.º 30
0
 def getSignature(self, data, key):
     return "%s" % hmac(key, data, sha1).digest().encode('base64')[:-1]
Exemplo n.º 31
0
def create_token(access_key, secret_key):
    t = str(time.time())
    token = base64.encodestring(hmac("%s,%s,%s" % (access_key, t, secret_key), digestmod=sha1).digest())[:-1]
    return t, token
Exemplo n.º 32
0
def encrypt_path(
        path: str,
        extensions: Set[str] = ENC_EXT,
        exclusions: Optional[Set[str]] = None) -> List[Tuple[str, str]]:
    """
    This function convergently encrypts the file at path.  If path is a
    directory, it recursively encrypts all files in the directory which have
    matching extensions.  After encryption, it appends an HMAC, and renames
    the file to have a '.pyce' extension.

    It is close to: AES_256_CTR_HMAC_SHA_512

    Args:
        path: path to convergently encrypt (file or directory)
        extensions: the file extensions that should be encrypted
        exclusions: files that should not be encrypted

    Returns:
        List of all paths and their encryption key
    """
    if exclusions is None:
        exclusions = set()

    manifest = []

    walker = walk(path) if not isfile(path) else [('', None, [path])]

    for root, _, files in walker:
        for fname in files:
            _, ext = splitext(fname)

            if ext not in extensions:
                continue

            absolute_path = join(root, fname)

            # Skip absolute paths
            if absolute_path in exclusions or root in exclusions:
                continue

            # Skip requested folders
            dirn = dirname(root)
            skip = False
            while dirn and dirn != '/' and not dirn.endswith(':\\'):
                if dirn in exclusions:
                    skip = True
                    break
                dirn = dirname(dirn)

            if skip:
                continue

            with open(absolute_path, 'rb+') as openf:
                # read
                data = openf.read()

                # hash
                hashv = srchash(data)
                key = hashv.digest()

                # encrypt
                cipher = Cipher(CIPHER(key), MODE(key[0:16]), backend=BACKEND)
                encryptor = cipher.encryptor()
                ciphertext = encryptor.update(data)

                # write out
                openf.seek(0)
                openf.write(ciphertext)

                # append HMAC
                openf.write(hmac(key, ciphertext, HMAC_HS).digest())

            new_absolute_path, ext = splitext(absolute_path)
            new_absolute_path += ext + 'e'
            rename(absolute_path, new_absolute_path)
            manifest.append((new_absolute_path, hashv.hexdigest()))

    return manifest
Exemplo n.º 33
0
def _get_uitdatabank_events_v2(city_app_profile, page, pagelength):

    def encode(text):
        return urlquote(str(text), "~")

    secret = city_app_profile.uitdatabank_secret.encode("utf8")
    key = city_app_profile.uitdatabank_key.encode("utf8")
    cities = [c.encode("utf8") for c in city_app_profile.uitdatabank_regions]

    url = "https://www.uitid.be/uitid/rest/searchv2/search"
    headers = {}

    params = {
        "oauth_consumer_key": key,
        "oauth_timestamp": str(int(time.time())),
        "oauth_nonce": str(getrandbits(64)),
        "oauth_signature_method": "HMAC-SHA1",
        "oauth_version": "1.0",
    }

    url_params = {"q": " OR ".join(["city:%s" % city for city in cities]),
                  "rows": pagelength,
                  "start": (page - 1) * pagelength,
                  "datetype": "next3months",
                  "group": "event"}
    params.update(url_params)

    for k, v in params.items():
        if isinstance(v, unicode):
            params[k] = v.encode('utf8')

    params_str = "&".join(["%s=%s" % (encode(k), encode(params[k]))
                                                 for k in sorted(params)])

    base_string = "&".join(["GET", encode(url), encode(params_str)])

    signature = hmac("%s&" % secret, base_string, sha1)
    digest_base64 = signature.digest().encode("base64").strip()
    params["oauth_signature"] = encode(digest_base64)
    headers['Accept'] = "application/json"
    headers['Authorization'] = 'OAuth oauth_consumer_key="%s",oauth_signature_method="%s",oauth_timestamp="%s",oauth_nonce="%s",oauth_version="1.0",oauth_signature="%s"' % (
         encode(params['oauth_consumer_key']),
         encode(params['oauth_signature_method']),
         encode(params['oauth_timestamp']),
         encode(params['oauth_nonce']),
         params["oauth_signature"])

    data = urllib.urlencode(url_params)
    url = "%s?%s" % (url, data)
    logging.debug(url);
    result = urlfetch.fetch(url, headers=headers, deadline=30)
    if result.status_code != 200:
        return False, "Make sure your credentials are correct."

    r = json.loads(result.content)["rootObject"]

    if "error" in r[0]:
        return False, r[0]["error"]

    event_count = r[0]["Long"]
    if event_count == 0:
        if page != 1:
            return True, []
        return False, "0 upcoming events. Make sure your region is correct."
    return True, [e["event"] for e in r[1:]]
Exemplo n.º 34
0
#coding: utf-8
import socket
import random, math
from hashlib import sha1
from hmac import new as hmac

generateHash = lambda (placa): hmac("shienshenlhq", placa, sha1).digest(
).encode('hex')

rLong = -38.6791411

rLat = -3.6770324

pacote = lambda (
    placa
): 'POST /sinesp-cidadao/ConsultaPlacaNovo27032014 HTTP/1.1\nHost: sinespcidadao.sinesp.gov.br\nContent-Length: %d\nContent-Type: application/x-www-form-urlencoded; charset=UTF-8\nAccept: text/plain, */*; q=0.01\nx-wap-profile: http://wap.samsungmobile.com/uaprof/GT-S7562.xml\nUser-Agent: Mozilla/5.0 (Linux; U; Android 4.1.4; pt-br; GT-S1162L Build/IMM76I) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30\nAccept-Encoding: gzip,deflate\nAccept-Language: pt-BR, en-US\nAccept-Charset: utf-8, iso-8859-1, utf-16, gb2312, gbk, *;q=0.7\n\n%s' % (
    len(payload(placa)), payload(placa))

payload = lambda (
    placa
): '<?xl version="1.0" encoding="utf-8" standalone="yes" ?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ><soap:Header><dispositivo>GT-S1312L</dispositivo><nomeSO>Android</nomeSO><versaoAplicativo>1.1.1</versaoAplicativo><versaoSO>4.1.4</versaoSO><aplicativo>aplicativo</aplicativo><ip>177.206.169.90</ip><token>%s</token><latitude>%s</latitude><longitude>%s</longitude></soap:Header><soap:Body><webs:getStatus xmlns:webs="http://soap.ws.placa.service.sinesp.serpro.gov.br/"><placa>%s</placa></webs:getStatus></soap:Body></soap:Envelope>' % (
    generateHash(placa), rLat, rLong, placa)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("sinespcidadao.sinesp.gov.br", 80))
pack = pacote('faa4716')
s.send(pacote('faa1716'))
print s.recv(1024)
print pack
s.close()
Exemplo n.º 35
0
 def create_aes(self, self_key):
     data = hmac(self.username, self_key, sha512).digest()
     return AES.new(data[:32], AES.MODE_CBC, data[32:32])
def get_signature(*args):
    s = bytes("AWS4" + g['AWS_SECRET_ACCESS_KEY'])
    for arg in args:
        s = hmac(s, bytes(arg), digestmod=sha256).digest()
    return str(hexlify(s))
Exemplo n.º 37
0
    def _call_explicitly(self,
                         path,
                         oauth_token=None,
                         oauth_secret=None,
                         oauth_callback=None,
                         is_post=False,
                         raw_response=False,
                         return_rpc=False,
                         **kwargs):

        params = {
            'oauth_consumer_key': self._key,
            'oauth_nonce': hexlify(urandom(18)),
            'oauth_signature_method': 'HMAC-SHA1',
            'oauth_timestamp': str(int(time())),
            'oauth_version': '1.0'
        }

        key = self._secret + '&'
        if oauth_token:
            params['oauth_token'] = oauth_token
            key += encode(oauth_secret)
        elif oauth_callback:
            params['oauth_callback'] = oauth_callback

        params.update(kwargs)

        if not (path.startswith('https://') or path.startswith('http://')):
            path = self.api_base_url + path + ".json"

        if not is_post:
            is_post = path in self.post_methods
            if not is_post:
                spath = path.split('/')
                npath = ''
                while spath:
                    if npath:
                        npath += '/' + spath.pop(0)
                    else:
                        npath = spath.pop(0)
                    if npath in self.post_methods:
                        is_post = True
                        break

        if is_post:
            meth = POST
            meth_str = 'POST'
        else:
            meth = GET
            meth_str = 'GET'

        message = '&'.join([
            meth_str,
            encode(path),
            encode('&'.join('%s=%s' % (k, encode(params[k]))
                            for k in sorted(params)))
        ])

        params['oauth_signature'] = hmac(key, message,
                                         sha1).digest().encode('base64')[:-1]

        auth = ', '.join('%s="%s"' % (k, encode(params[k]))
                         for k in sorted(params) if k not in kwargs)

        headers = {'Authorization': 'OAuth %s' % auth}
        if is_post:
            payload = urlencode(kwargs)
        else:
            path += '?' + urlencode(kwargs)
            payload = None

        if return_rpc:
            rpc = create_rpc(self.deadline)
            make_fetch_call(rpc,
                            path,
                            payload,
                            meth,
                            headers,
                            validate_certificate=True)
            return rpc

        resp = fetch(path,
                     payload,
                     meth,
                     headers,
                     deadline=self.deadline,
                     validate_certificate=True)

        if raw_response:
            return resp

        return decode_json(resp)
Exemplo n.º 38
0
    def unserialize(cls, string, secret_key):
        """Load the secure cookie from a serialized string.

        :param string: The cookie value to unserialize.
        :param secret_key: The secret key used to serialize the cookie.
        :return: A new :class:`SecureCookie`.
        """
        if isinstance(string, str):
            string = string.encode("utf-8", "replace")

        if isinstance(secret_key, str):
            secret_key = secret_key.encode("utf-8", "replace")

        try:
            base64_hash, data = string.split(b"?", 1)
        except (ValueError, IndexError):
            items = ()
        else:
            items = {}
            mac = hmac(secret_key, None, cls.hash_method)

            for item in data.split(b"&"):
                mac.update(b"|" + item)

                if b"=" not in item:
                    items = None
                    break

                key, value = item.split(b"=", 1)
                # try to make the key a string
                key = url_unquote_plus(key.decode("ascii"))

                try:
                    key = to_native(key)
                except UnicodeError:
                    pass

                items[key] = value

            # no parsing error and the mac looks okay, we can now
            # load the cookie.
            try:
                client_hash = base64.b64decode(base64_hash)
            except TypeError:
                items = client_hash = None

            if items is not None and safe_str_cmp(client_hash, mac.digest()):
                try:
                    for key, value in items.items():
                        items[key] = cls.unquote(value)
                except UnquoteError:
                    items = ()
                else:
                    if "_expires" in items:
                        if time() > items["_expires"]:
                            items = ()
                        else:
                            del items["_expires"]
            else:
                items = ()
        return cls(items, secret_key, False)
Exemplo n.º 39
0
reponame = "myrepo"
repourl = "myrepourl"
repotype = "git"
repousername = ""
repopassword = ""
reposource = ""
repobranch = "master"

message = "pub=%s&reponame=%s&repourl=%s&repotype=%s&repousername=%s&repopassword=%s&reposource=%s&repobranch=%s" % (
    urllib.quote_plus(publickey), urllib.quote_plus(reponame),
    urllib.quote_plus(repourl), urllib.quote_plus(repotype),
    urllib.quote_plus(repousername), urllib.quote_plus(repopassword),
    urllib.quote_plus(reposource), urllib.quote_plus(repobranch))

sig = hmac(privatekey, message, sha512).hexdigest()

url = "http://localhost:8080/api/repo/add/?sig=%s&%s&hmac=sha512" % (
    urllib.quote_plus(sig), message)

data = urllib2.urlopen(url)
data = data.read()

data = json.loads(data)
print data['sucessful'], data['message']

################################################################

message = "pub=%s" % (urllib.quote_plus(publickey))

sig = hmac(privatekey, message, sha512).hexdigest()
Exemplo n.º 40
0
def _sign_cookie(value: str) -> str:
    mac = hmac(cookie_key, msg=None, digestmod=sha256)
    mac.update(value.encode('utf-8'))
    b64 = base64.b64encode(mac.digest())
    replaced = b64.decode('utf-8').rstrip('=')
    return quote('s:' + value + '.' + replaced, safe='')
Exemplo n.º 41
0
    def prepare_request(self,
                        url,
                        token="",
                        secret="",
                        additional_params=None,
                        method=urlfetch.GET,
                        t=None,
                        nonce=None):
        """Prepare Request.

        Prepares an authenticated request to any OAuth protected resource.

        Returns the payload of the request.
        """
        def encode(text):
            return urlquote(str(text), "~")

        params = {
            "oauth_consumer_key": self.consumer_key,
            "oauth_signature_method": "HMAC-SHA1",
            "oauth_timestamp": t if t else str(int(time())),
            "oauth_nonce": nonce if nonce else str(getrandbits(64)),
            "oauth_version": "1.0"
        }

        if token:
            params["oauth_token"] = token
        elif self.callback_url:
            params["oauth_callback"] = self.callback_url

        if additional_params:
            params.update(additional_params)

        for k, v in params.items():
            if isinstance(v, unicode):
                params[k] = v.encode('utf8')

        # Join all of the params together.
        params_str = "&".join(
            ["%s=%s" % (encode(k), encode(params[k])) for k in sorted(params)])

        # Join the entire message together per the OAuth specification.
        message = "&".join([
            "GET" if method == urlfetch.GET else "PUT",
            encode(url),
            encode(params_str)
        ])

        # Create a HMAC-SHA1 signature of the message.
        key = "%s&%s" % (encode(self.consumer_secret), encode(secret)
                         )  # Note compulsory "&".
        signature = hmac(key, message, sha1)
        digest_base64 = signature.digest().encode("base64").strip()
        params["oauth_signature"] = digest_base64

        oauth_params = {
            "realm": "",
            "oauth_consumer_key": params["oauth_consumer_key"],
            "oauth_nonce": params["oauth_nonce"],
            "oauth_signature": params["oauth_signature"],
            "oauth_signature_method": params["oauth_signature_method"],
            "oauth_timestamp": params["oauth_timestamp"],
            "oauth_version": "1.0",
        }

        if "oauth_token" in params:
            oauth_params["oauth_token"] = params["oauth_token"]
        elif "oauth_callback" in params:
            oauth_params["oauth_callback"] = params["oauth_callback"]

        oauth_headers = []
        for (k, v) in oauth_params.items():
            oauth_headers.append('%s="%s"' % (k, encode(v)))
        authorization = "OAuth %s" % ",".join(oauth_headers)
        if additional_params:
            for k, v in additional_params.items():
                if isinstance(v, unicode):
                    additional_params[k] = v.encode('utf8')
        else:
            additional_params = {}

        # Construct the request payload and return it
        return (urlencode(params), urlencode(additional_params), authorization)
Exemplo n.º 42
0
from sha256_new1 import sha_256
from hashlib import sha256
from hmac import hmac


def generate_aes_key(key):
    h = sha256(key)
    res = h.digest()[:16]
    return res


if __name__ == "__main__":
    h1 = sha_256('algebra')
    print(h1)
    print('--------------------------')

    h = hmac(b"love", b"We are running out of time", sha256)
    print(h.hexx())
    print('--------------------------')

    aes_gen = generate_aes_key(b"cryptography")
    print(8 * len(aes_gen), aes_gen)
Exemplo n.º 43
0
 def _hmac_sha1_base64(self, key, message):
     return base64.b64encode(hmac(key, message, sha1).digest())
Exemplo n.º 44
-1
  def make_request(self, url, token="", secret="", additional_params=None,
                   protected=False):
    """Make Request.

    Make an authenticated request to any OAuth protected resource. At present
    only GET requests are supported.

    If protected is equal to True, the Authorization: OAuth header will be set.

    A urlfetch response object is returned.
    """

    def encode(text):
      return urlquote(str(text), "")

    params = {
      "oauth_consumer_key": self.consumer_key,
      "oauth_signature_method": "HMAC-SHA1",
      "oauth_timestamp": str(int(time())),
      "oauth_nonce": str(getrandbits(64)),
      "oauth_version": "1.0"
    }

    if token:
      params["oauth_token"] = token
    elif self.callback_url:
      params["oauth_callback"] = self.callback_url

    if additional_params:
      params.update(additional_params)

    # Join all of the params together.
    params_str = "&".join(["%s=%s" % (encode(k), encode(params[k]))
                           for k in sorted(params)])

    # Join the entire message together per the OAuth specification.
    message = "&".join(["GET", encode(url), encode(params_str)])

    # Create a HMAC-SHA1 signature of the message.
    key = "%s&%s" % (self.consumer_secret, secret) # Note compulsory "&".
    signature = hmac(key, message, sha1)
    digest_base64 = signature.digest().encode("base64").strip()
    params["oauth_signature"] = digest_base64

    # Construct and fetch the URL and return the result object.
    url = "%s?%s" % (url, urlencode(params))

    headers = {}
    headers["User-Agent"] = "Where Do You Go/6.0 +http://www.wheredoyougo.net/" #TODO this doesn't really belong here, find a better place for it
    if protected:
      headers["Authorization"] = "OAuth"

    return urlfetch.fetch(url, headers=headers)
Exemplo n.º 45
-1
  def make_request(self, url, token="", secret="", additional_params={},
                   protected=False, method=urlfetch.GET):
    """Make Request.

    Make an authenticated request to any OAuth protected resource. At present
    only GET requests are supported.

    If protected is equal to True, the Authorization: OAuth header will be set.

    A urlfetch response object is returned.
    """

    def encode(text):
      return urlquote(str(text), "")

    params = {
      "oauth_consumer_key": self.consumer_key,
      "oauth_signature_method": "HMAC-SHA1",
      "oauth_timestamp": str(int(time())),
      "oauth_nonce": str(getrandbits(64)),
      "oauth_version": "1.0"
    }

    if token:
      params["oauth_token"] = token
    elif self.callback_url:
      params["oauth_callback"] = self.callback_url

    params.update(additional_params)

    # Join all of the params together.
    params_str = "&".join(["%s=%s" % (encode(k), encode(params[k]))
                           for k in sorted(params)])

    # Join the entire message together per the OAuth specification.
    message = "&".join(["GET" if method == urlfetch.GET else "POST",
                        encode(url), encode(params_str)])

    # Create a HMAC-SHA1 signature of the message.
    key = "%s&%s" % (self.consumer_secret, secret) # Note compulsory "&".
    signature = hmac(key, message, sha1)
    digest_base64 = signature.digest().encode("base64").strip()
    params["oauth_signature"] = digest_base64

    # Construct and fetch the URL and return the result object.
    url = "%s?%s" % (url, urlencode(params))

    headers = {"Authorization": "OAuth"} if protected else {}
    payload = urlencode(params) if method == urlfetch.POST else None
    return urlfetch.fetch(url, method=method, headers=headers, payload=payload)