import json
import hmac
import hashlib
import base64


def signed_serialize(data, secret):
    """ Serialize any pickleable structure (``data``) and sign it
    using the ``secret`` (must be a string).  Return the
    serialization, which includes the signature as its first 40 bytes.
    The ``signed_deserialize`` method will deserialize such a value.
    This function is useful for creating signed cookies.  For example:
    .. code-block:: python
       cookieval = signed_serialize({'a':1}, 'secret')
       response.set_cookie('signed_cookie', cookieval)
    """
    payload = json.dumps(data).encode('utf-8')
    sig = hmac.new(secret, payload, hashlib.sha1).hexdigest()
    return sig.encode('utf-8') + base64.b64encode(payload)