+def DumpSignedJson(data, key, salt=None, key_selector=None):
+ """Serialize a given object and authenticate it.
+
+ @param data: the data to serialize
+ @param key: shared hmac key
+ @param key_selector: name/id that identifies the key (in case there are
+ multiple keys in use, e.g. in a multi-cluster environment)
+ @return: the string representation of data signed by the hmac key
+
+ """
+ txt = DumpJson(data)
+ if salt is None:
+ salt = ""
+ signed_dict = {
+ "msg": txt,
+ "salt": salt,
+ }
+
+ if key_selector:
+ signed_dict["key_selector"] = key_selector
+ else:
+ key_selector = ""
+
+ signed_dict["hmac"] = utils.Sha1Hmac(key, txt, salt=salt + key_selector)
+
+ return DumpJson(signed_dict)
+
+
+def LoadSignedJson(txt, key):
+ """Verify that a given message was signed with the given key, and load it.
+
+ @param txt: json-encoded hmac-signed message
+ @param key: the shared hmac key or a callable taking one argument (the key
+ selector), which returns the hmac key belonging to the key selector.
+ Typical usage is to pass a reference to the get method of a dict.
+ @rtype: tuple of original data, string
+ @return: original data, salt
+ @raises errors.SignatureError: if the message signature doesn't verify
+
+ """
+ signed_dict = LoadJson(txt)
+ if not isinstance(signed_dict, dict):
+ raise errors.SignatureError("Invalid external message")
+ try:
+ msg = signed_dict["msg"]
+ salt = signed_dict["salt"]
+ hmac_sign = signed_dict["hmac"]
+ except KeyError:
+ raise errors.SignatureError("Invalid external message")
+
+ if callable(key):
+ # pylint: disable=E1103
+ key_selector = signed_dict.get("key_selector", None)
+ hmac_key = key(key_selector)
+ if not hmac_key:
+ raise errors.SignatureError("No key with key selector '%s' found" %
+ key_selector)
+ else:
+ key_selector = ""
+ hmac_key = key
+
+ if not utils.VerifySha1Hmac(hmac_key, msg, hmac_sign,
+ salt=salt + key_selector):
+ raise errors.SignatureError("Invalid Signature")
+
+ return LoadJson(msg), salt
+
+