private static void AddOscoreKey(string[] cmds) { if (cmds.Length != 3) { Console.WriteLine("Incorrect number of arguments: " + cmds.Length); return; } CBORObject cbor = CBORDiagnostics.Parse(cmds[2]); byte[] salt = null; if (cbor.ContainsKey(CBORObject.FromObject(6))) { salt = cbor[CBORObject.FromObject(6)].GetByteString(); } byte[] contextId = null; if (cbor.ContainsKey(CBORObject.FromObject(7))) { contextId = cbor[CBORObject.FromObject(7)].GetByteString(); } SecurityContext ctx = SecurityContext.DeriveContext( cbor[CBORObject.FromObject(1)].GetByteString(), contextId, cbor[CBORObject.FromObject(2)].GetByteString(), cbor[CBORObject.FromObject(3)].GetByteString(), salt, null /*cbor[CoseKeyKeys.Algorithm]*/); Program._OscoreKeys.Add(cmds[1], ctx); }
static Signer GetSigner(CBORObject control) { CBORObject alg = GetAttribute(control, "alg"); if (control.ContainsKey("alg")) { control.Remove(CBORObject.FromObject("alg")); } JWK key = GetKey(control["key"]); Signer signer; signer = new Signer(key, alg.AsString()); if (control.ContainsKey("protected")) { AddAttributes(signer, control["protected"], 0); } if (control.ContainsKey("unprotected")) { AddAttributes(signer, control["unprotected"], 1); } if (control.ContainsKey("unsent")) { AddAttributes(signer, control["unsent"], 2); } return(signer); }
public Signer(CBORObject jsonSigner) { if (jsonSigner.ContainsKey("protected")) { protectedB64 = jsonSigner["protected"].AsString(); ProtectedMap = CBORObject.FromJSONString(Encoding.UTF8.GetString(Message.base64urldecode(jsonSigner["protected"].AsString()))); if (ProtectedMap.Count == 0) { throw new JoseException("field 'protected' must be omitted for empty maps."); } } if (jsonSigner.ContainsKey("header")) { UnprotectedMap = jsonSigner["header"]; } else if (ProtectedMap.Count == 0) { throw new JoseException("One of 'protected' or 'header' must be present."); } if (!jsonSigner.ContainsKey("signature")) { throw new JoseException("Field 'signature' must be present."); } signature = Message.base64urldecode(jsonSigner["signature"].AsString()); }
static Message ProcessSign(CBORObject control, ref bool fDirty) { CBORObject input = control["input"]; CBORObject sign = input["sign"]; CBORObject signers; SignMessage msg = new SignMessage(); if (!input.ContainsKey("plaintext")) { throw new Exception("missing plaintext field"); } msg.SetContent(input["plaintext"].AsString()); if (sign.ContainsKey("protected")) { AddAttributes(msg, sign["protected"], 0); } if (sign.ContainsKey("unprotected")) { AddAttributes(msg, sign["unprotected"], 1); } if (sign.ContainsKey("unsent")) { AddAttributes(msg, sign["unsent"], 2); } if ((!sign.ContainsKey("signers")) || (sign["signers"].Type != CBORType.Array)) { throw new Exception("Missing or malformed recipients"); } foreach (CBORObject recip in sign["signers"].Values) { msg.AddSigner(GetSigner(recip)); } { msg.Encode(); signers = Program.GetSection(Program.GetSection(control, "intermediates"), "signers", CBORType.Array); for (int iSigner = 0; iSigner < msg.SignerList.Count; iSigner++) { while (signers.Count < msg.SignerList.Count) { signers.Add(CBORObject.NewMap()); } Program.SetField(signers[iSigner], "ToBeSign", msg.SignerList[iSigner].ToBeSigned, ref fDirty); } } return(msg); }
private bool CompareField(Key key2, CBORObject key) { if (m_map.ContainsKey(key)) { if (!key2.m_map.ContainsKey(key)) { return(false); } return(m_map[key].CompareTo(key2.m_map[key]) == 0); } else { return(!key2.m_map.ContainsKey(key)); } }
private void GetSignature(CBORObject statement) { if (statement.ContainsKey("sig")) { Signature = statement["sig"].ToObject <byte[]>(); } }
static CBORObject GetAttribute(CBORObject obj, string attrName) { if (obj.ContainsKey("protected") && obj["protected"].ContainsKey(attrName)) { return(obj["protected"][attrName]); } if (obj.ContainsKey("unprotected") && obj["unprotected"].ContainsKey(attrName)) { return(obj["unprotected"][attrName]); } if (obj.ContainsKey("unsent") && obj["unsent"].ContainsKey(attrName)) { return(obj["unsent"][attrName]); } return(null); }
static void SetReceivingAttributes(Signer recip, CBORObject control) { if (control.ContainsKey("unsent")) { AddAttributes(recip, control["unsent"], 2); } }
public CBORObject FindAttribute(CBORObject label) { if (objProtected.ContainsKey(label)) { return(objProtected[label]); } if (objUnprotected.ContainsKey(label)) { return(objUnprotected[label]); } if (objDontSend.ContainsKey(label)) { return(objDontSend[label]); } return(null); }
private void GetAlgorithm(CBORObject statement) { if (statement.ContainsKey("alg")) { Algorithm = (COSE.Algorithm)statement["alg"].AsInt32(); } }
/// <inheritdoc /> protected override string InternalEncodeCompressed() { CBORObject objBody; CBORObject objSigners = null; if (SignerList.Count != 1) { throw new JoseException("Compact mode not supported if more than one signer"); } if (UnprotectedMap.Count > 0) { throw new JoseException("Compact mode not supported if unprotected attributes exist"); } objBody = EncodeToJSON(); // Base64 encoding says kill some messages if (objBody.ContainsKey("signatures")) { objSigners = objBody["signatures"][0]; } string str = ""; if (objSigners != null && objSigners.ContainsKey("protected")) { str += objSigners["protected"].AsString(); } str += "."; if (objBody.ContainsKey("payload")) { if (objBody["payload"].AsString().Contains('.')) { throw new Exception("Message cannot contain a period character"); } str += objBody["payload"].AsString(); } str += "."; if (objSigners != null && objSigners.ContainsKey("signature")) { str += objSigners["signature"].AsString(); } return(str); }
static void BuildCompact(CBORObject control, JwkSet keys) { // Encrypted or Signed? if (control.ContainsKey("signing")) { SignMessage sign = new SignMessage(); Signer signer = new Signer(keys[0]); sign.SetContent(control["input"]["payload"].AsString()); sign.AddSigner(signer); CBORObject xx = control["signing"]["protected"]; foreach (CBORObject key in xx.Keys) { signer.AddAttribute(key, xx[key], Attributes.PROTECTED); } string output = sign.EncodeCompressed(); Message msg = Message.DecodeFromString(output); CheckMessage(msg, keys[0], control["input"]); } else if (control.ContainsKey("encrypting_key")) { EncryptMessage enc = new EncryptMessage(); CBORObject xx = control["encrypting_content"]["protected"]; foreach (CBORObject key in xx.Keys) { enc.AddAttribute(key, xx[key], Attributes.PROTECTED); } Recipient recip = new Recipient(keys[0], control["input"]["alg"].AsString(), enc); enc.AddRecipient(recip); enc.SetContent(control["input"]["plaintext"].AsString()); string output = enc.EncodeCompressed(); Message msg = Message.DecodeFromString(output); CheckMessage(msg, keys[0], control["input"]); } }
public void TestCPOD() { var m = new CPOD(); m.Aa = "Test"; CBORObject cbor = CBORObject.FromObject(m); Assert.IsFalse(cbor.ContainsKey("bb"), cbor.ToString()); Assert.AreEqual("Test", cbor["aa"].AsString(), cbor.ToString()); }
protected bool getKeyValueAsBool(CBORObject obj, string key) { if (obj.ContainsKey(key)) { return(obj[key].AsBoolean()); } else { return(false); } }
public void DecodeFromJSON(CBORObject json) { if (json.Type != CBORType.Map) { throw new JoseException("recipient must be a map"); } if (json.ContainsKey("header")) { UnprotectedMap = json["header"]; if (UnprotectedMap.Type != CBORType.Map || UnprotectedMap.Count == 0) { throw new JoseException("field 'header' must be a non-empty map"); } } if (json.ContainsKey("encrypted_key")) { _rgbEncrypted = Message.base64urldecode(json["encrypted_key"].AsString()); } }
private void GetCertificates(CBORObject statement) { if (statement.ContainsKey("x5c")) { var certs = new List <X509Certificate2>(); var data = statement["x5c"].ToObject <byte[][]>(); foreach (var cert in data) { certs.Add(new X509Certificate2(cert)); } Certificates = certs.ToArray(); } }
public static Message DecodeFromJSON(CBORObject message) { if (message.ContainsKey("ciphertext")) { EncryptMessage msgx = new EncryptMessage(); msgx.InternalDecodeFromJSON(message); return(msgx); } SignMessage signMessage = new SignMessage(); signMessage.InternalDecodeFromJSON(message); return(signMessage); }
/// <summary> /// See if a field in two keys is the same /// </summary> /// <param name="key2">2nd key to use</param> /// <param name="label">label of field to compare</param> /// <returns></returns> private bool CompareField(OneKey key2, CBORObject label) { if (_map.ContainsKey(label)) { if (!key2._map.ContainsKey(label)) { return(false); } return(_map[label].Equals(key2._map[label])); } else { return(!key2._map.ContainsKey(label)); } }
static Recipient SetReceivingAttributes(Recipient recip, CBORObject control) { JWK key = null; if (control.ContainsKey("unsent")) { AddAttributes(recip, control["unsent"], 2); } if (control["key"] != null) { key = GetKey(control["key"]); } recip.SetKey(key); return(recip); }
/// <summary> /// What the CBOR structure needs to look like: /// /// </summary> /// <param name="cmds"></param> private static void AddGroupOscoreKey(string[] cmds) { if (cmds.Length != 3) { Console.WriteLine("Incorrect number of arguments: " + cmds.Length); return; } CBORObject cbor = CBORDiagnostics.Parse(cmds[2]); byte[] salt = null; if (cbor.ContainsKey(CoseKeyKeys.slt)) { salt = cbor[CoseKeyKeys.slt].GetByteString(); } SecurityContext ctx = SecurityContext.DeriveGroupContext(cbor[CoseKeyParameterKeys.Octet_k].GetByteString(), cbor[CBORObject.FromObject("GroupID")].GetByteString(), cbor[CBORObject.FromObject("sender")][CBORObject.FromObject("ID")].GetByteString(), cbor["sender"]["sign"][CoseKeyKeys.Algorithm], new OneKey(cbor["sender"]["sign"]), null, null, salt, cbor[CoseKeyKeys.Algorithm]); ctx.CountersignParams = cbor["ParCS"]; ctx.CountersignKeyParams = cbor["ParCSKey"]; foreach (CBORObject recipient in cbor[CBORObject.FromObject("recipients")].Values) { OneKey signKey = null; if (recipient.ContainsKey("sign")) { signKey = new OneKey(recipient["sign"]); } ctx.AddRecipient(recipient[CBORObject.FromObject("ID")].GetByteString(), signKey); } ctx.Locate = (context, kid) => { Console.WriteLine("Looking for a kid with a value of " + ByteArrayUtils.ToHexString(kid)); return(null); }; Program._OscoreKeys.Add(cmds[1], ctx); }
static Com.AugustCellars.JOSE.Recipient GetRecipient(CBORObject control) { Com.AugustCellars.JOSE.JWK key; if (!control.ContainsKey("alg")) { throw new Exception("Recipient missing alg field"); } if (control.ContainsKey("key")) { key = new Com.AugustCellars.JOSE.JWK(control["key"]); } else if (control.ContainsKey("pwd")) { key = new Com.AugustCellars.JOSE.JWK(); key.Add("kty", "oct"); key.Add("k", Com.AugustCellars.JOSE.Message.base64urlencode(Encoding.UTF8.GetBytes(control["pwd"].AsString()))); } else { throw new Exception("No key defined for a recipient"); } Com.AugustCellars.JOSE.Recipient recipient = new Com.AugustCellars.JOSE.Recipient(key, control["alg"].AsString()); // Double check that alg is the same as in the attributes recipient.ClearProtected(); recipient.ClearUnprotected(); if (control.ContainsKey("protected")) { AddAttributes(recipient, control["protected"], 0); } if (control.ContainsKey("unprotected")) { AddAttributes(recipient, control["unprotected"], 1); } if (control.ContainsKey("sender_key")) { Com.AugustCellars.JOSE.JWK myKey = new Com.AugustCellars.JOSE.JWK(control["sender_key"]); recipient.SetSenderKey(myKey); } return(recipient); }
public static CBORObject Patch(CBORObject o, CBORObject ptch) { // clone the object in case of failure if (o == null) { throw new ArgumentNullException(nameof(o)); } o = CloneCbor(o); if (ptch == null) { throw new ArgumentNullException(nameof(ptch)); } for (int i = 0; i < ptch.Count; ++i) { CBORObject patchOp = ptch[i]; // NOTE: This algorithm requires "op" to exist // only once; the CBORObject, however, does not // allow duplicates string valueOpStr = GetString(patchOp, "op"); if (valueOpStr == null) { throw new ArgumentException("Patch"); } if ("add".Equals(valueOpStr, StringComparison.Ordinal)) { // operation CBORObject value = null; if (!patchOp.ContainsKey("value")) { throw new ArgumentException("Patch " + valueOpStr + " value"); } value = patchOp["value"]; o = AddOperation(o, valueOpStr, GetString(patchOp, "path"), value); } else if ("replace".Equals(valueOpStr, StringComparison.Ordinal)) { // operation CBORObject value = null; if (!patchOp.ContainsKey("value")) { throw new ArgumentException("Patch " + valueOpStr + " value"); } value = patchOp["value"]; o = ReplaceOperation( o, valueOpStr, GetString(patchOp, "path"), value); } else if ("remove".Equals(valueOpStr, StringComparison.Ordinal)) { // Remove operation string path = patchOp["path"].AsString(); if (path == null) { throw new ArgumentException("Patch " + valueOpStr + " path"); } if (path.Length == 0) { o = null; } else { RemoveOperation(o, valueOpStr, GetString(patchOp, "path")); } } else if ("move".Equals(valueOpStr, StringComparison.Ordinal)) { string path = patchOp["path"].AsString(); if (path == null) { throw new ArgumentException("Patch " + valueOpStr + " path"); } string fromPath = patchOp["from"].AsString(); if (fromPath == null) { throw new ArgumentException("Patch " + valueOpStr + " from"); } if (path.StartsWith(fromPath, StringComparison.Ordinal)) { throw new ArgumentException("Patch " + valueOpStr); } CBORObject movedObj = RemoveOperation(o, valueOpStr, fromPath); o = AddOperation(o, valueOpStr, path, CloneCbor(movedObj)); } else if ("copy".Equals(valueOpStr, StringComparison.Ordinal)) { string path = patchOp["path"].AsString(); string fromPath = patchOp["from"].AsString(); if (path == null) { throw new ArgumentException("Patch " + valueOpStr + " path"); } if (fromPath == null) { throw new ArgumentException("Patch " + valueOpStr + " from"); } JSONPointer pointer = JSONPointer.FromPointer(o, path); if (!pointer.Exists()) { throw new KeyNotFoundException("Patch " + valueOpStr + " " + fromPath); } CBORObject copiedObj = pointer.GetValue(); o = AddOperation( o, valueOpStr, path, CloneCbor(copiedObj)); } else if ("test".Equals(valueOpStr, StringComparison.Ordinal)) { string path = patchOp["path"].AsString(); if (path == null) { throw new ArgumentException("Patch " + valueOpStr + " path"); } CBORObject value = null; if (!patchOp.ContainsKey("value")) { throw new ArgumentException("Patch " + valueOpStr + " value"); } value = patchOp["value"]; JSONPointer pointer = JSONPointer.FromPointer(o, path); if (!pointer.Exists()) { throw new ArgumentException("Patch " + valueOpStr + " " + path); } Object testedObj = pointer.GetValue(); if ((testedObj == null) ? (value != null) : !testedObj.Equals(value)) { throw new InvalidOperationException("Patch " + valueOpStr); } } } return((o == null) ? CBORObject.Null : o); }
private static string GetString(CBORObject o, string key) { return(o.ContainsKey(key) ? o[key].AsString() : null); }
public void Process(Request request, Response response) { // Is this processable? if (response.StatusCode != StatusCode.Unauthorized || response.ContentFormat != 65008) { return; } try { // Init from the response data Oauth.AsInfo info = new Oauth.AsInfo(response.Payload); // Missage this as needed. string aSServer = info.ASServer; // Need to build one from scratch if (!authServers.ContainsKey(info.ASServer)) { Console.WriteLine($"No security association is setup for {info.ASServer}"); return; } AuthServerInfo asi = authServers[info.ASServer]; if (asi.ClientLink == null) { asi.ClientLink = new CoapClient(new Uri(info.ASServer)); if (asi.UseDTLS) { asi.ClientLink.EndPoint = new DTLSClientEndPoint(asi.TlsKey); asi.ClientLink.EndPoint.Start(); } } // M00BUG - need to make sure that this will pickup a port number if given. string audience = $"{request.URI.Scheme}://{request.URI.Authority}"; Oauth.Request myRequest = new Oauth.Request("client_credentials") { Audience = audience, Scope = CBORObject.FromObject(request.UriPath) }; myRequest.Profile = Profile; byte[] payload = myRequest.EncodeToBytes(); asi.ClientLink.Timeout = 2 * 60 * 1000; Response asResponse = asi.ClientLink.Post(payload, MediaType.ApplicationCbor); if (asResponse == null) { asi.ClientLink.EndPoint.Stop(); asi.ClientLink = null; Console.WriteLine($"Timed out requesting token from {info.ASServer}"); return; } if (asResponse.StatusCode != StatusCode.Created) { // We had an error condition appear if (asResponse.Payload != null) { CBORObject obj = CBORObject.DecodeFromBytes(asResponse.Payload); int error = obj["error"].AsInt32(); string errorText = ""; if (obj.ContainsKey("error_description")) { errorText = obj["error_description"].AsString(); } Console.WriteLine( $"Recieved an error {asResponse.StatusCode} with error no = {error} and description '{errorText}'"); } else { Console.WriteLine($"Received and error {asResponse.StatusCode} from the AS but no text"); } return; } Oauth.Response myResponse = new Oauth.Response(asResponse.Payload); // default profile for client - #if false if (Profile != null && myResponse.Profile != Profile) { Console.WriteLine("AS Server returned an unexpected profile {0}", myResponse.Profile); return; } #endif myResponse.Profile = Oauth.ProfileIds.Coap_Dtls; // Post token to resource server CoapClient client = new CoapClient(); client.Uri = new Uri($"coap://{request.URI.Authority}/authz-info"); client.Timeout = 10000; // 1 second Response tknResponse = client.Post(myResponse.Token, MediaType.ApplicationCbor); if (tknResponse == null) { Console.WriteLine("Post of token failed w/ no response"); return; } if (tknResponse.StatusCode != StatusCode.Created) { Console.WriteLine($"Post of token failed with error {tknResponse.StatusCode}"); return; } Confirmation cnf = myResponse.Confirmation; Request newRequest = new Request(request.Method); newRequest.Payload = request.Payload; newRequest.SetOptions(request.GetOptions()); DTLSClientEndPoint endPoint = null; switch (myResponse.Profile) { case Oauth.ProfileIds.Coap_Dtls: { OneKey key = cnf.Key; endPoint = new DTLSClientEndPoint(cnf.Key); endPoint.Start(); newRequest.EndPoint = endPoint; newRequest.URI = new Uri($"coaps://{request.URI.Authority}/{request.URI.AbsolutePath}"); } break; case Oauth.ProfileIds.Coap_Oscore: { OneKey oneKey = cnf.Key; byte[] salt = null; if (oneKey.ContainsName("slt")) { salt = oneKey[CBORObject.FromObject("slt")].GetByteString(); } CBORObject alg = null; if (oneKey.ContainsName(CoseKeyKeys.Algorithm)) { alg = oneKey[CoseKeyKeys.Algorithm]; } CBORObject kdf = null; if (oneKey.ContainsName(CBORObject.FromObject("kdf"))) { kdf = oneKey[CBORObject.FromObject("kdf")]; } SecurityContext oscoapContext = SecurityContext.DeriveContext( oneKey[CoseKeyParameterKeys.Octet_k].GetByteString(), oneKey[CBORObject.FromObject("sid")].GetByteString(), oneKey[CBORObject.FromObject("rid")].GetByteString(), salt, alg, kdf); newRequest.OscoapContext = oscoapContext; } break; default: Console.WriteLine("Cannot rewrite as we don't recognize the profile"); return; } newRequest.Respond += delegate(Object sender, ResponseEventArgs e) { Response responseN = e.Response; if (responseN == null) { Console.WriteLine("Request timeout"); } else { Console.WriteLine(Utils.ToString(responseN)); Console.WriteLine("Time (ms): " + responseN.RTT); } if (endPoint != null) { endPoint.Stop(); } }; newRequest.Send(); } catch (Exception e) { Console.WriteLine("Error processing AceAuthz - " + e.ToString()); } }
static bool ValidateEnveloped(CBORObject control) { CBORObject input = control["input"]; CBORObject encrypt = input["enveloped"]; if ((!encrypt.ContainsKey("recipients")) || (encrypt["recipients"].Type != CBORType.Array)) { throw new Exception("Missing or malformed recipients"); } for (int iRecipient = 0; iRecipient < encrypt["recipients"].Count; iRecipient++) { bool fFail = HasFailMarker(control) || HasFailMarker(encrypt); EncryptMessage encryptMessage; try { Message message; CBORObject obj = control["output"]["json"]; if (obj.Type == CBORType.TextString) { message = Message.DecodeFromString(obj.AsString()); } else { message = Message.DecodeFromJSON(obj); } encryptMessage = (EncryptMessage)message; } catch (Exception) { if (fFail) { return(true); } return(false); } if (encrypt.ContainsKey("unsent")) { AddAttributes(encryptMessage, encrypt["unsent"], 2); } CBORObject recipient = encrypt["recipients"][iRecipient]; Recipient recipientMessage = encryptMessage.RecipientList[iRecipient]; recipientMessage = SetReceivingAttributes(recipientMessage, recipient); /* * if (recipient["sender_key"] != null) * { * if (recipientMessage.FindAttribute(HeaderKeys.StaticKey) == null) * { * recipientMessage.AddAttribute(HeaderKeys.StaticKey, GetKey(recipient["sender_key"], true).AsCBOR(), * Attributes.DO_NOT_SEND); * } * } */ bool fFailRecipient = HasFailMarker(recipient); try { encryptMessage.Decrypt(recipientMessage); if (encryptMessage.GetContentAsString() != input["plaintext"].AsString()) { return(false); } } catch (Exception) { if (fFail || fFailRecipient) { return(true); } return(false); } } return(true); }
/// <inheritdoc /> protected override void InternalDecodeFromJSON(CBORObject json) { // Parse out the message from the JSON if (json.ContainsKey("signatures")) { if (json.ContainsKey("signature")) { throw new JoseException("Cannot have both 'signatures' and 'signature' present."); } CBORObject signers = json["signatures"]; if (signers.Type != CBORType.Array || signers.Count == 0) { throw new JoseException("field 'signatures' must be a non-empty array."); } 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); } else { throw new JoseException("field 'signatures' or 'signature' must be present."); } if (json.ContainsKey("payload")) { CBORObject b64 = SignerList[0].FindAttribute(CBORObject.FromObject("b64"), PROTECTED); if (b64 != null) { if (b64.Type != CBORType.Boolean) { throw new Exception("Invalid message"); } if (b64.AsBoolean()) { payloadB64 = Encoding.UTF8.GetBytes(json["payload"].AsString()); payload = base64urldecode(json["payload"].AsString()); } else { payload = Encoding.UTF8.GetBytes(json["payload"].AsString()); payloadB64 = payload; } } else { payloadB64 = Encoding.UTF8.GetBytes(json["payload"].AsString()); payload = base64urldecode(json["payload"].AsString()); } } else { throw new JoseException("field 'payload' must be present."); } }
public Boolean ContainsName(string name) { return(_json.ContainsKey(name)); }
private static IEnumerable <WebLink> ParseCommon(CBORObject links, Dictionary <string, CBORObject> dictionary) { if (links.Type != CBORType.Array) { throw new ArgumentException("Not an array"); } for (int i = 0; i < links.Count; i++) { CBORObject resource = links[i]; if (resource.Type != CBORType.Map) { throw new ArgumentException("Element not correctly formatted"); } string name; if (resource.ContainsKey("href")) { name = resource["href"].AsString(); } else { name = resource[CBORObject.FromObject(1)].AsString(); } WebLink link = new WebLink(name); foreach (CBORObject key in resource.Keys) { string keyName = null; if (dictionary != null && key.Type == CBORType.Number) { foreach (KeyValuePair <string, CBORObject> kvp in dictionary) { if (key.Equals(kvp.Value)) { keyName = kvp.Key; break; } } } if (keyName == null) { keyName = key.AsString(); } if (ParseStrictMode && SingleOccuranceAttributes.Contains(keyName)) { throw new ArgumentException($"'{keyName}' occurs multiple times"); } CBORObject value = resource[key]; if (value.Type == CBORType.Boolean) { link.Attributes.Add(name); } else if (value.Type == CBORType.TextString) { link.Attributes.Add(name, value.AsString()); } else if (value.Type == CBORType.Array) { for (int i1 = 0; i1 < value.Count; i1++) { if (value.Type == CBORType.Boolean) { link.Attributes.Add(name); } else if (value.Type == CBORType.TextString) { link.Attributes.Add(name, value.AsString()); } else { throw new ArgumentException("incorrect type"); } } } else { throw new ArgumentException("incorrect type"); } } yield return(link); } }
protected override void InternalDecodeFromJSON(CBORObject json) { if (json.ContainsKey("protected")) { _strProtected = json["protected"].AsString(); ProtectedMap = CBORObject.FromJSONString(Encoding.UTF8.GetString(base64urldecode(_strProtected))); if (ProtectedMap.Type != CBORType.Map || ProtectedMap.Count == 0) { throw new JoseException("field 'protected' must be a non-empty map"); } } else { ProtectedMap = CBORObject.NewMap(); } // Can be absent if (json.ContainsKey("unprotected")) { UnprotectedMap = json["unprotected"]; if (UnprotectedMap.Type != CBORType.Map || UnprotectedMap.Count == 0) { throw new JoseException("field 'unprotected' must be a non-empty map"); } } else { UnprotectedMap = CBORObject.NewMap(); } if (json.ContainsKey("iv")) { _iv = base64urldecode(json["iv"].AsString()); } else { _iv = null; } if (json.ContainsKey("aad")) { _Aad = base64urldecode(json["aad"].AsString()); _Aad = Encoding.UTF8.GetBytes(json["aad"].AsString()); } else { _Aad = null; } if (!json.ContainsKey("ciphertext")) { throw new JoseException("field 'ciphertext' must be present"); } _RgbEncrypted = base64urldecode(json["ciphertext"].AsString()); if (json.ContainsKey("tag")) { _Tag = base64urldecode(json["tag"].AsString()); } else { _Tag = null; } if (json.ContainsKey("recipients")) { CBORObject recips = json["recipients"]; if (recips.Type != CBORType.Array || recips.Count == 0) { throw new JoseException("field 'recipients' must be a non-empty array"); } bool needHeaders = (ProtectedMap.Count + UnprotectedMap.Count) == 0; for (int i = 0; i < recips.Count; i++) { Recipient recipient = new Recipient(); recipient.DecodeFromJSON(recips[i]); RecipientList.Add(recipient); if (needHeaders) { if (recipient.ProtectedMap.Count + recipient.UnprotectedMap.Count == 0) { throw new JoseException("One of protected, unprotected or headers must be present for every recipient"); } } } } else { // Look at ths as a flattened version Recipient recipient = new Recipient(); recipient.DecodeFromJSON(json); RecipientList.Add(recipient); if (recipient.ProtectedMap.Count + recipient.UnprotectedMap.Count + ProtectedMap.Count + UnprotectedMap.Count == 0) { throw new JoseException("One of protected, unprotected or headers must be present for every recipient"); } } }
/// <inheritdoc /> protected override string InternalEncodeCompressed() { CBORObject obj3; CBORObject objRecip = null; string str = ""; if (RecipientList.Count() != 1) { throw new JoseException("Compact encoding cannot have more than one recipient"); } if (_Aad != null) { throw new JoseException("Compact encoding cannot have additional authenticated data"); } if (RecipientList[0].UnprotectedMap.Count != 0) { if (_RgbEncrypted == null) { foreach (CBORObject o in RecipientList[0].UnprotectedMap.Keys) { ProtectedMap.Add(o, RecipientList[0].UnprotectedMap[o]); } RecipientList[0].UnprotectedMap.Clear(); } } ForceArray(true); obj3 = EncodeToJSON(); if (obj3.ContainsKey("recipients")) { objRecip = obj3["recipients"][0]; } if (obj3.ContainsKey("aad")) { throw new JoseException("Compact encoding cannot have additional authenticated data"); } if (objRecip != null && objRecip.ContainsKey("header")) { throw new JoseException("Compact encoding cannot have recipient header data"); } if (obj3.ContainsKey("protected")) { str += obj3["protected"].AsString(); } str += "."; if (obj3.ContainsKey("unprotected")) { throw new JoseException("Compact encoding cannot have unprotected attributes"); } if (objRecip != null && objRecip.ContainsKey("encrypted_key")) { str += objRecip["encrypted_key"].AsString(); } str += "."; if (obj3.ContainsKey("iv")) { str += obj3["iv"].AsString(); } str += "."; if (obj3.ContainsKey("ciphertext")) { str += obj3["ciphertext"].AsString(); } str += "."; if (obj3.ContainsKey("tag")) { str += obj3["tag"].AsString(); } return(str); }