ruma::signatures

Function sign_json

Source
pub fn sign_json<K>(
    entity_id: &str,
    key_pair: &K,
    object: &mut BTreeMap<String, CanonicalJsonValue>,
) -> Result<(), Error>
where K: KeyPair,
Available on crate feature signatures only.
Expand description

Signs an arbitrary JSON object and adds the signature to an object under the key signatures.

If signatures is already present, the new signature will be appended to the existing ones.

§Parameters

  • entity_id: The identifier of the entity creating the signature. Generally this means a homeserver, e.g. “example.com”.
  • key_pair: A cryptographic key pair used to sign the JSON.
  • object: A JSON object to sign according and append a signature to.

§Errors

Returns an error if:

  • object contains a field called signatures that is not a JSON object.

§Examples

A homeserver signs JSON with a key pair:

const PKCS8: &str = "\
    MFECAQEwBQYDK2VwBCIEINjozvdfbsGEt6DD+7Uf4PiJ/YvTNXV2mIPc/\
    tA0T+6tgSEA3TPraTczVkDPTRaX4K+AfUuyx7Mzq1UafTXypnl0t2k\
";

let document: Base64 = Base64::parse(PKCS8).unwrap();

// Create an Ed25519 key pair.
let key_pair = ruma_signatures::Ed25519KeyPair::from_der(
    document.as_bytes(),
    "1".into(), // The "version" of the key.
)
.unwrap();

// Deserialize some JSON.
let mut value = serde_json::from_str("{}").unwrap();

// Sign the JSON with the key pair.
assert!(ruma_signatures::sign_json("domain", &key_pair, &mut value).is_ok());

This will modify the JSON from an empty object to a structure like this:

{
    "signatures": {
        "domain": {
            "ed25519:1": "K8280/U9SSy9IVtjBuVeLr+HpOB4BQFWbg+UZaADMtTdGYI7Geitb76LTrr5QV/7Xg4ahLwYGYZzuHGZKM5ZAQ"
        }
    }
}