def make_token_data(slave_ip, valid_from, valid_to, chaff_bytes=16): """Return a string suitable for using as token data. This string will be signed, and the signature passed back to clients as the token key.""" chaff = b64(os.urandom(chaff_bytes)) block = "%s:%s:%s:%s" % (slave_ip, valid_from, valid_to, chaff) return block
def verify_nonce(self, token, nonce): if self.redis: next_nonce_digest = self.redis.get( "%s:nonce:%s" % (self.redis_prefix, b64sha1sum(token))) else: next_nonce_digest = self.nonces.get(token) if next_nonce_digest is None: return False for secret in self.token_secrets: if sign_data(nonce, secret) == next_nonce_digest: break else: # We tried all secrets and they all failed return False # Generate the next one valid_to = unpack_token_data(self.tokens[token])['valid_to'] next_nonce = b64(os.urandom(16)) self.save_nonce(token, next_nonce, valid_to) return next_nonce
def sign_data(data, secret, hsh=hashlib.sha256): """Returns b64(hmac(secret, data))""" h = hmac.new(secret, data, hsh) return b64(h.digest())