public SignMessage(JSON json) { // Parse out the message from the JSON if (json.ContainsKey("signatures")) { JSON signers = json["signatures"]; for (int i = 0; i < signers.Count; i++) { Signer signer = new Signer(signers[i]); signerList.Add(signer); } } else if (json.ContainsKey("signature")) { Signer signer = new Signer(json); signerList.Add(signer); } if (json.ContainsKey("payload")) { JSON b64 = signerList[0].FindAttribute("b64", true); if (b64 != null) { if (b64.nodeType != JsonType.boolean) { throw new Exception("Invalid message"); } if (b64.AsBoolean()) { payloadB64 = UTF8Encoding.UTF8.GetBytes(json["payload"].AsString()); payload = base64urldecode(json["payload"].AsString()); } else { payload = UTF8Encoding.UTF8.GetBytes(json["payload"].AsString()); payloadB64 = payload; } } else { payloadB64 = UTF8Encoding.UTF8.GetBytes(json["payload"].AsString()); payload = base64urldecode(json["payload"].AsString()); } } }
public JSON EncodeToJSON() { JSON obj = new JSON(); if (objUnprotected.Count > 0) { obj.Add("unprotected", objUnprotected); // Add unprotected attributes } // Look at the world of base64 encoded bodies. // If any signer has the b64 false, then all of them need to. // Then change our body if needed int b64Found = 0; bool b64Value = true; foreach (Signer key in signerList) { JSON attr = key.FindAttribute("b64", true); if (attr != null) { if (b64Found == 0) { b64Value = attr.AsBoolean(); } else if (b64Value != attr.AsBoolean()) { throw new JOSE_Exception("Not all signers using the same value for b64"); } b64Found += 1; } } if (b64Value) { obj.Add("payload", base64urlencode(payload)); } else { if (b64Found != signerList.Count) { throw new JOSE_Exception("Not all signers using the same value for b64"); } obj.Add("payload", UTF8Encoding.UTF8.GetString(payload)); } if ((signerList.Count == 1) && !forceAsArray) { JSON recipient = signerList[0].EncodeToJSON(payload); foreach (KeyValuePair <string, JSON> pair in recipient.map) { obj.Add(pair.Key, pair.Value); } } else if (signerList.Count > 0) { JSON signers = new JSON(); foreach (Signer key in signerList) { signers.Add(key.EncodeToJSON(payload)); } obj.Add("signatures", signers); } return(obj); }