/// <summary> /// Stringify a message. /// </summary> public static string ToString(Message msg) { StringBuilder sb = new StringBuilder(); string kind = "Message", code = "Code"; if (msg.IsRequest) { kind = "Request"; code = "Method"; } else if (msg.IsResponse) { kind = "Response"; code = "Status"; } sb.AppendFormat("==[ COAP {0} ]============================================\n", kind) .AppendFormat("ID : {0}\n", msg.ID) .AppendFormat("Type : {0}\n", msg.Type) .AppendFormat("Token : {0}\n", msg.TokenString) .AppendFormat("{1}: {0}\n", Code.ToString(msg.Code), code.PadRight(7)); if (msg.Source != null) { sb.AppendFormat("Source : {0}\n", msg.Source); } if (msg.Destination != null) { sb.AppendFormat("Dest : {0}\n", msg.Destination); } sb.AppendFormat("Options: {0}\n", OptionsToString(msg)) .AppendFormat("Payload: {0} Bytes\n", msg.PayloadSize); if (msg.PayloadSize > 0) { sb.AppendLine("---------------------------------------------------------------"); if (MediaType.IsPrintable(msg.ContentType)) { sb.AppendLine(msg.PayloadString); } else if (MediaType.IsCbor(msg.ContentType)) { sb.AppendLine(CBORObject.DecodeFromBytes(msg.Payload).ToString()); } else { string x = Hex.ToHexString(msg.Payload); for (int i = 0; i < x.Length; i += 64) { int chunk = (i + 64 < x.Length) ? 64 : (x.Length - i); sb.AppendLine(x.Substring(i, chunk)); } } } return(sb.ToString()); }
protected static EU_DGC GetVaccinationProofFromCbor(byte[] cborData) { CBORObject cbor = CBORObject.DecodeFromBytes(cborData, CBOREncodeOptions.Default); EU_DGC vacProof = EU_DGC.FromJson(cbor.ToJSONString()); return(vacProof); }
public CounterSignature(byte[] rgBytes) { context = "CounterSignature"; CBORObject cbor = CBORObject.DecodeFromBytes(rgBytes); ((Signer)this).DecodeFromCBORObject(cbor); }
protected override void DoPost(CoapExchange exchange) { try { Request request = exchange.Request; CBORObject obj = CBORObject.DecodeFromBytes(request.Payload); exchange.Accept(); String uri = obj[0].AsString(); byte[] key = obj[1].GetByteString(); List <SecurityContext> contexts = SecurityContextSet.AllContexts.FindByKid(key); if (contexts.Count == 0) { exchange.Respond(StatusCode.BadRequest, "No matching key identifier found"); return; } Codec.IMessageDecoder me = Spec.Default.NewMessageDecoder(obj[2].GetByteString()); Request newRequest = me.DecodeRequest(); newRequest.URI = new System.Uri(uri); newRequest.OscoapContext = contexts[0]; newRequest.Send(); Response response = newRequest.WaitForResponse(); exchange.Respond(response); } catch (Exception e) { exchange.Respond(StatusCode.BadRequest, e.ToString()); } }
public void TestIncompleteIndefLengthMap() { // Premature end after value byte[] bytes = { 0xbf, 0x61, 0x41, 0, 0x61, 0x42, 0 }; try { CBORObject.DecodeFromBytes(bytes); Assert.Fail("Should have failed"); } catch (CBORException) { // NOTE: Intentionally empty } catch (Exception ex) { Assert.Fail(ex.ToString()); throw new InvalidOperationException(String.Empty, ex); } // Premature end after key bytes = new byte[] { 0xbf, 0x61, 0x41, 0, 0x61, 0x42 }; try { CBORObject.DecodeFromBytes(bytes); Assert.Fail("Should have failed"); } catch (CBORException) { // NOTE: Intentionally empty } catch (Exception ex) { Assert.Fail(ex.ToString()); throw new InvalidOperationException(String.Empty, ex); } bytes = new byte[] { 0xbf, 0x61, 0x41, 0, 0x61, 0x42, 0, 0xff }; try { CBORObject.DecodeFromBytes(bytes); } catch (Exception ex) { Assert.Fail(ex.ToString()); throw new InvalidOperationException(String.Empty, ex); } }
public IPublicKey Parse(byte[] publicKeyCoseBuffer) { var cbor = CBORObject.DecodeFromBytes(publicKeyCoseBuffer); var alg = cbor[3].AsNumber().ToInt32Checked(); return(_publicKeyFactory.Create(alg, cbor)); }
public void TestSharedRefs() { var encodeOptions = new CBOREncodeOptions("resolvereferences=true"); byte[] bytes; CBORObject cbor; string expected; bytes = new byte[] { 0x9f, 0xd8, 28, 1, 0xd8, 29, 0, 3, 3, 0xd8, 29, 0, 0xff, }; cbor = CBORObject.DecodeFromBytes(bytes, encodeOptions); expected = "[1,1,3,3,1]"; Assert.AreEqual(expected, cbor.ToJSONString()); bytes = new byte[] { 0x9f, 0xd8, 28, 0x81, 1, 0xd8, 29, 0, 3, 3, 0xd8, 29, 0, 0xff, }; cbor = CBORObject.DecodeFromBytes(bytes, encodeOptions); expected = "[[1],[1],3,3,[1]]"; Assert.AreEqual(expected, cbor.ToJSONString()); // Checks if both objects are the same reference, not just equal Assert.IsTrue(cbor[0] == cbor[1], "cbor[0] not same as cbor[1]"); Assert.IsTrue(cbor[0] == cbor[4], "cbor[0] not same as cbor[4]"); bytes = new byte[] { 0xd8, 28, 0x82, 1, 0xd8, 29, 0 }; cbor = CBORObject.DecodeFromBytes(bytes, encodeOptions); Assert.AreEqual(2, cbor.Count); // Checks if both objects are the same reference, not just equal Assert.IsTrue(cbor == cbor[1], "objects not the same"); }
protected CBORObject decodeFromBytes(byte[] byteresponse) { CBORObject cbor = null; //Bad authenticator response such as communication error if (byteresponse == null) { return(null); } // Status Status = byteresponse[0]; StatusMsg = CTAPResponse.GetMessage(Status); if (byteresponse.Length > 1) { try { // CBOR var cobrbyte = byteresponse.Skip(1).ToArray(); cbor = CBORObject.DecodeFromBytes(cobrbyte, CBOREncodeOptions.Default); ResponsePayloadJson = cbor.ToJSONString(); Logger.Log($"Recv: {ResponsePayloadJson}"); } catch (Exception ex) { Logger.Log($"CBOR DecordError:{ex.Message}"); } } return(cbor); }
public void TestStringRefs() { var encodeOptions = new CBOREncodeOptions("resolvereferences=true"); CBORObject cbor = CBORObject.DecodeFromBytes( new byte[] { 0xd9, 1, 0, 0x9f, 0x64, 0x61, 0x62, 0x63, 0x64, 0xd8, 0x19, 0x00, 0xd8, 0x19, 0x00, 0x64, 0x62, 0x62, 0x63, 0x64, 0xd8, 0x19, 0x01, 0xd8, 0x19, 0x00, 0xd8, 0x19, 0x01, 0xff, }, encodeOptions); string expected = "[\"abcd\",\"abcd\",\"abcd\",\"bbcd\",\"bbcd\",\"abcd\",\"bbcd\"]"; Assert.AreEqual(expected, cbor.ToJSONString()); cbor = CBORObject.DecodeFromBytes(new byte[] { 0xd9, 1, 0, 0x9f, 0x64, 0x61, 0x62, 0x63, 0x64, 0x62, 0x61, 0x61, 0xd8, 0x19, 0x00, 0xd8, 0x19, 0x00, 0x64, 0x62, 0x62, 0x63, 0x64, 0xd8, 0x19, 0x01, 0xd8, 0x19, 0x00, 0xd8, 0x19, 0x01, 0xff, }, encodeOptions); expected = "[\"abcd\",\"aa\",\"abcd\",\"abcd\",\"bbcd\",\"bbcd\",\"abcd\",\"bbcd\"]"; Assert.AreEqual(expected, cbor.ToJSONString()); }
private void ResponseRecieved(object sender, ResponseEventArgs e) { if (e.Response.ContentType == 60) // 60 -> cbor { try { CborModel = CBORObject.DecodeFromBytes(e.Response.Payload); } catch (PeterO.Cbor.CBORException) { //Take some action } BeginInvoke(new Action(() => PayloadDataTextBox.Text = CborModel.ToJSONString())); } else if (e.Response.ContentType == 0) // 0 - text/plain { BeginInvoke(new Action(() => PayloadDataTextBox.Text = e.Response.Payload.ToString())); } else if (e.Response.ContentType == 40) { LinkCollection collection = new LinkCollection(e.Response.PayloadString); StringBuilder stringBuilder = new StringBuilder(); foreach (var item in collection) { stringBuilder.AppendLine(item.Uri); } BeginInvoke(new Action(() => PayloadDataTextBox.Text = stringBuilder.ToString())); } }
public PNGrantTokenDecoded GetPermissions(string token) { token = token.Replace("-", "+").Replace("_", "/"); int i = token.Length % 4; if (i != 0) { token += new String('=', 4 - i); } #if (ENABLE_PUBNUB_LOGGING) this.PubNubInstance.PNLog.WriteToLog(token, PNLoggingMethod.LevelInfo); #endif PNGrantTokenDecoded pnGrantTokenDecoded = new PNGrantTokenDecoded(); pnGrantTokenDecoded.Patterns = new GrantResources { Channels = new Dictionary <string, int>(), Groups = new Dictionary <string, int>(), Users = new Dictionary <string, int>(), Spaces = new Dictionary <string, int>() }; pnGrantTokenDecoded.Resources = new GrantResources { Channels = new Dictionary <string, int>(), Groups = new Dictionary <string, int>(), Users = new Dictionary <string, int>(), Spaces = new Dictionary <string, int>() }; pnGrantTokenDecoded.Meta = new Dictionary <string, object>(); byte[] decryptedBytes = Convert.FromBase64CharArray(token.ToCharArray(), 0, token.Length); var cbor = CBORObject.DecodeFromBytes(decryptedBytes); ParseCBOR(cbor, "", ref pnGrantTokenDecoded); return(pnGrantTokenDecoded); }
public void DecodeFromCBORObject(CBORObject obj) { if (obj.Count != 4) { throw new CoseException("Invalid MAC structure"); } // Protected values. if (obj[0].Type == CBORType.ByteString) { byte[] data = obj[0].GetByteString(); if (data.Length == 0) { objProtected = CBORObject.NewMap(); } else { objProtected = CBORObject.DecodeFromBytes(data); if (objProtected.Type != CBORType.Map) { throw new CoseException("Invalid MAC Structure"); } } } else { throw new CoseException("Invalid MAC structure"); } // Unprotected attributes if (obj[1].Type == PeterO.Cbor.CBORType.Map) { objUnprotected = obj[1]; } else { throw new CoseException("Invalid MAC Structure"); } // Plain Text if (obj[2].Type == CBORType.ByteString) { rgbContent = obj[2].GetByteString(); } else if (!obj[2].IsNull) // Detached content - will need to get externally { throw new CoseException("Invalid MAC Structure"); } // Authentication tag if (obj[3].Type == CBORType.ByteString) { rgbTag = obj[3].GetByteString(); } else { throw new CoseException("Invalid MAC Structure"); } }
public AttestationObject(byte[] data) { var cbor = CBORObject.DecodeFromBytes(data); Format = cbor["fmt"].AsString(); AttestationStatement = new AttestationStatement(cbor["attStmt"], Format); AuthenticatorData = new AuthenticatorData(cbor["authData"].ToObject <byte[]>()); }
public void TestConstructors() { Cori cori = new Cori("coap://host:99"); Assert.ThrowsException <ArgumentException>(() => new CoralBody(CBORObject.DecodeFromBytes(Hex.Decode("01")), cori, null)); Assert.ThrowsException <ArgumentException>(() => new CoralBody(CBORObject.DecodeFromBytes(Hex.Decode("830202820500")), cori, null)); CoralBody body = new CoralBody(CBORObject.DecodeFromBytes(Hex.Decode("81830202820500")), cori, _testDictionary); Assert.AreEqual(1, body.Length); Assert.AreEqual("http://www.iana.org/assignments/relation/collection", ((CoralLink)body[0]).RelationTypeText); body = new CoralBody(CBORObject.DecodeFromBytes(Hex.Decode("828302028205008302006377766F")), cori, _testDictionary); Assert.AreEqual(2, body.Length); Assert.AreEqual("http://www.iana.org/assignments/relation/collection", ((CoralLink)body[0]).RelationTypeText); Assert.AreEqual("http://www.w3.org/1999/02/22-rdf-syntax-ns#type", ((CoralLink)body[1]).RelationTypeText); // [ // [2 // [0, "http", 1, "apps.augustcellars.com", 5, "rel1"], // [5, "target1"], // [ // [2, // [0, "http", 1, "apps.augustcellars.com", 5, "rel2"], // [4, 1, 5, "target2"]], [1, [0, "coap", 1, "host3", 5, "link1"]], [2, [0, "http", 1, "apps.augustcellars.com", 5, "rel2"], [4, 1, 5, "target2"]]]], [2, [0, "http", 1, "apps.augustcellars.com", 5, "rel3"], [5, "target2"]], [1, [0, "http", 1, "host", 5, "link2", 5, "link3"]], [2, [0, "http", 1, "apps.augustcellars.com", 5, "rel4"], [4, 1, 5, "target2"]], [3, [0, "http", 1, "apps.augustcellars.com", 5, "op-type"], [4, 1, 5, "form"]]] body = new CoralBody(CBORObject.DecodeFromBytes(Hex.Decode("858402860064687474700176617070732E61756775737463656C6C6172732E636F6D056472656C3182056774617267657431838302860064687474700176617070732E61756775737463656C6C6172732E636F6D056472656C328404010567746172676574328201860064636F61700165686F73743305656C696E6B318302860064687474700176617070732E61756775737463656C6C6172732E636F6D056472656C328404010567746172676574328302860064687474700176617070732E61756775737463656C6C6172732E636F6D056472656C33820567746172676574328201880064687474700164686F737405656C696E6B3205656C696E6B338302860064687474700176617070732E61756775737463656C6C6172732E636F6D056472656C348404010567746172676574328303860064687474700176617070732E61756775737463656C6C6172732E636F6D05676F702D747970658404010564666F726D")), cori, _testDictionary); Assert.AreEqual(5, body.Length); Assert.IsTrue(body[0] is CoralLink); Assert.IsTrue(body[1] is CoralLink); Assert.IsTrue(body[2] is CoralBaseDirective); Assert.IsTrue(body[3] is CoralLink); Assert.IsTrue(body[4] is CoralForm); CoralLink link = (CoralLink)body[0]; Assert.AreEqual("coap://host:99/target1", link.Target.ToString()); Assert.AreEqual(3, link.Body.Length); Assert.IsTrue(link.Body[0] is CoralLink); Assert.IsTrue(link.Body[1] is CoralBaseDirective); Assert.IsTrue(link.Body[2] is CoralLink); CoralLink link2 = (CoralLink)link.Body[0]; Assert.AreEqual("coap://host:99/target1/target2", link2.Target.ToString()); link2 = (CoralLink)link.Body[2]; Assert.AreEqual("coap://host3/link1/target2", link2.Target.ToString()); link = (CoralLink)body[1]; Assert.AreEqual("coap://host:99/target2", link.Target.ToString()); link = (CoralLink)body[3]; Assert.AreEqual("http://host/link2/link3/target2", link.Target.ToString()); Assert.AreEqual("http://host/link2/link3/form", ((CoralForm)body[4]).Target.ToString()); }
private static SecurityContextSet LoadContextSet(string fileName) { if (fileName == null) { fileName = "ServerKeys.cbor"; } KeySet keys = new KeySet(); SecurityContextSet newSet = new SecurityContextSet(); FileStream fs = new FileStream(fileName, FileMode.Open); using (BinaryReader reader = new BinaryReader(fs)) { byte[] data = reader.ReadBytes((int)fs.Length); CBORObject obj = CBORObject.DecodeFromBytes(data); for (int i = 0; i < obj.Count; i++) { OneKey key = new OneKey(obj[i]); string[] usages = key[_UsageKey].AsString().Split(' '); foreach (String usage in usages) { if (usage == "oscoap") { SecurityContext ctx = SecurityContext.DeriveContext( key[CoseKeyParameterKeys.Octet_k].GetByteString(), null, key[CBORObject.FromObject("RecipID")].GetByteString(), key[CBORObject.FromObject("SenderID")].GetByteString(), null, key[CoseKeyKeys.Algorithm]); newSet.Add(ctx); break; } else if (usage == "oscoap-group") { SecurityContext ctx = SecurityContext.DeriveGroupContext( key[CoseKeyParameterKeys.Octet_k].GetByteString(), key[CBORObject.FromObject(2)].GetByteString(), key[CBORObject.FromObject("SenderID")].GetByteString(), null, null, null, null, null, key[CoseKeyKeys.Algorithm]); foreach (CBORObject recipient in key[CBORObject.FromObject("recipients")].Values) { ctx.AddRecipient(recipient[CBORObject.FromObject("RecipID")].GetByteString(), new OneKey(recipient[CBORObject.FromObject("sign")])); } newSet.Add(ctx); } } if ((usages.Length != 1) || (usages[0] != "oscoap")) { keys.AddKey(key); } } reader.Close(); } // return(newSet); }
/// <summary> /// Given a first message in the Edhoc protocol, parse the message into pieces /// and fill in the data struture elements to continue processing. /// Throw an exception on failures. /// </summary> /// <param name="msgData"></param> /// <returns></returns> public static EdhocResponder ParseMessage1(byte[] msgData) { EdhocResponder edhoc = new EdhocResponder(); CBORObject msg = CBORObject.DecodeFromBytes(msgData); if (msg.Type != CBORType.Array) { throw new Exception("Invalid message"); } if (msg[0].AsInt32() == 1) { edhoc._fSymmetricSecret = false; } else if (msg[0].AsInt32() == 4) { edhoc._fSymmetricSecret = true; } else { throw new Exception("Invalid Message"); } // Fill in "their" data into the different arrays edhoc._Messages[0] = msgData; // message_1 edhoc._SessionId[1] = msg[1].GetByteString(); edhoc._Nonce[1] = msg[2].GetByteString(); edhoc._Keys[1] = new OneKey(msg[3]); // Their one time key edhoc._algKeyAgree = _SelectAlgorithm(msg[4], new CBORObject[] { AlgorithmValues.ECDH_SS_HKDF_256 }); edhoc._algAEAD = _SelectAlgorithm(msg[5], new CBORObject[] { AlgorithmValues.AES_CCM_64_64_128 }); if (!edhoc._fSymmetricSecret) { edhoc._algSign = _SelectAlgorithm(msg[6], new CBORObject[] { AlgorithmValues.ECDSA_256 }); } else { edhoc._kid[1] = msg[6]; } edhoc._Keys[0] = OneKey.GenerateKey(null, edhoc._Keys[1][CoseKeyKeys.KeyType], "X25519" /*edhoc._Keys[1][CoseKeyParameterKeys.EC_Curve].AsString()*/); #if true edhoc._SessionId[0] = new byte[2]; edhoc._random.NextBytes(edhoc._SessionId[0]); edhoc._Nonce[0] = new byte[8]; edhoc._random.NextBytes(edhoc._Nonce[0]); #else edhoc._SessionId[0] = Encoding.UTF8.GetBytes("Kid Svr"); edhoc._Nonce[0] = Encoding.UTF8.GetBytes("Server Nonce"); #endif MessageList.Add(new ListKey(edhoc._SessionId[0]), edhoc); return(edhoc); }
public static (byte[] unitsSnapshot, byte[] trainControlSnapshot, CBORObject simInfoSnapshot) UnglueFullSimSnapshot(byte[] fullSimSnapshot) { // MEGA HACK FOR MVP var cbor = CBORObject.DecodeFromBytes(fullSimSnapshot); return(cbor["units"].ToObject <byte[]>(), cbor["trainControl"].ToObject <byte[]>(), cbor["simInfo"] ); }
/// <summary> /// Create a CWT based on the passed in byte. /// </summary> /// <param name="data">initial value</param> public CWT(byte[] data) { CBORObject cbor = CBORObject.DecodeFromBytes(data); if (cbor.Type != CBORType.Map) { throw new CwtException("CWT must be a map"); } _claims = cbor; }
static CoralBody DecodeFromBytes(byte[] encoded, CoralDictionary dictionary = null) { CBORObject obj = CBORObject.DecodeFromBytes(encoded); if (dictionary == null) { dictionary = CoralDictionary.Default; } return(new CoralBody(obj, dictionary)); }
/** * Constructor creating a CWT from a supplied encoding. * * @param data * the encoding * @throws CBORException * if the supplied encoding is not a valid CWT */ public CWT(byte[] data) { CBORObject obj = CBORObject.DecodeFromBytes(data); if (obj.Type != CBORType.Map) { throw new CBORException("Not a valid CWT"); } CwtObject = obj; }
public void TestNegativeBigInts() { Assert.AreEqual( EInteger.FromString("-257"), CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x42, 1, 0 }).AsEInteger()); Assert.AreEqual( EInteger.FromString("-65537"), CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x43, 1, 0, 0 }).AsEInteger()); { object objectTemp = EInteger.FromString("-16777217"); object objectTemp2 = CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x44, 1, 0, 0, 0 }).AsEInteger(); Assert.AreEqual(objectTemp, objectTemp2); } { object objectTemp = EInteger.FromString("-4294967297"); object objectTemp2 = CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x45, 1, 0, 0, 0, 0 }).AsEInteger(); Assert.AreEqual(objectTemp, objectTemp2); } { object objectTemp = EInteger.FromString("-1099511627777"); object objectTemp2 = CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x46, 1, 0, 0, 0, 0, 0 }).AsEInteger(); Assert.AreEqual(objectTemp, objectTemp2); } { object objectTemp = EInteger.FromString("-281474976710657"); object objectTemp2 = CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x47, 1, 0, 0, 0, 0, 0, 0 }).AsEInteger(); Assert.AreEqual(objectTemp, objectTemp2); } { object objectTemp = EInteger.FromString("-72057594037927937"); object objectTemp2 = CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x48, 1, 0, 0, 0, 0, 0, 0, 0 }).AsEInteger(); Assert.AreEqual(objectTemp, objectTemp2); } { object objectTemp = EInteger.FromString("-18446744073709551617"); object objectTemp2 = CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x49, 1, 0, 0, 0, 0, 0, 0, 0, 0 }).AsEInteger(); Assert.AreEqual(objectTemp, objectTemp2); } { object objectTemp = EInteger.FromString("-4722366482869645213697"); object objectTemp2 = CBORObject.DecodeFromBytes(new byte[] { 0xc3, 0x4a, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }).AsEInteger(); Assert.AreEqual(objectTemp, objectTemp2); } }
virtual public void DecodeFromCBORObject(CBORObject messageObject) { if (messageObject.Count != 4) { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[0].Type == CBORType.ByteString) { if (messageObject[0].GetByteString().Length == 0) { objProtected = CBORObject.NewMap(); } else { rgbProtected = messageObject[0].GetByteString(); objProtected = CBORObject.DecodeFromBytes(rgbProtected); if (objProtected.Count == 0) { rgbProtected = new byte[0]; } } } else { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[1].Type == CBORType.Map) { objUnprotected = messageObject[1]; } else { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[2].Type == CBORType.ByteString) { rgbContent = messageObject[2].GetByteString(); } else if (!messageObject[2].IsNull) { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[3].Type == CBORType.ByteString) { rgbSignature = messageObject[3].GetByteString(); } else { throw new CoseException("Invalid Sign1 structure"); } }
protected static async Task <CTAPResponseInner> sendCommandandResponse(DevParam devParam, byte[] send, int timeoutms) { var response = new CTAPResponseInner(); byte[] byteresponse = null; // HID if (devParam.hidparams != null) { var res = await CTAPHID.SendCommandandResponse(devParam.hidparams, send, timeoutms); if (res != null) { if (res.isTimeout == true) { response.Status = -2; return(response); } response.DevType = 1; byteresponse = res.responseData; } } // NFC if (byteresponse == null && devParam.nfcparams != null) { byteresponse = CTAPNFC.SendCommandandResponse(devParam.nfcparams, send); if (byteresponse != null) { response.DevType = 2; } } if (byteresponse == null) { response.Status = -1; return(response); } response.StatusCodeCTAP = byteresponse[0]; if (byteresponse.Length > 1) { try { var cobrbyte = byteresponse.Skip(1).ToArray(); response.ResponseDataCbor = CBORObject.DecodeFromBytes(cobrbyte, CBOREncodeOptions.Default); var json = response.ResponseDataCbor.ToJSONString(); System.Diagnostics.Debug.WriteLine($"Recv: {json}"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"CBOR DecordError:{ex.Message}"); } } return(response); }
protected override void InternalDecodeFromCBORObject(CBORObject messageObject) { if (messageObject.Count != 4) { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[0].Type == CBORType.ByteString) { if (messageObject[0].GetByteString().Length == 0) { ProtectedMap = CBORObject.NewMap(); } else { ProtectedBytes = messageObject[0].GetByteString(); ProtectedMap = CBORObject.DecodeFromBytes(ProtectedBytes); if (ProtectedMap.Count == 0) { ProtectedBytes = new byte[0]; } } } else { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[1].Type == CBORType.Map) { UnprotectedMap = messageObject[1]; } else { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[2].Type == CBORType.ByteString) { rgbContent = messageObject[2].GetByteString(); } else if (!messageObject[2].IsNull) { throw new CoseException("Invalid Sign1 structure"); } if (messageObject[3].Type == CBORType.ByteString) { _rgbSignature = messageObject[3].GetByteString(); } else { throw new CoseException("Invalid Sign1 structure"); } }
public void CreateMessage1_1() { EdhocInitiator e = new EdhocInitiator(keyOctet); byte[] val = e.CreateMessage1(); Assert.That(val, !Is.EqualTo(null)); CBORObject obj = CBORObject.DecodeFromBytes(val); Assert.That(obj.Type, Is.EqualTo(CBORType.Array)); Assert.That(obj.Count, Is.EqualTo(7)); }
public static void VerifySignature(PublicKeyCredential cred, byte[] authData, byte[] clientData, byte[] signature, string rpid) { if (cred == null) { throw new ArgumentNullException(nameof(cred)); } var payload = authData.Concat(CredentialUtility.Hash(clientData)).ToArray(); var rawSignature = DERSignature.Deserialize(signature); var authDataSpan = authData.AsSpan(); var rpidHash = authDataSpan.Slice(0, 32); var flags = (AuthenticatorDataFlags)authDataSpan[32]; var counterSpan = authDataSpan.Slice(33, 4); counterSpan.Reverse(); uint counter = BitConverter.ToUInt32(counterSpan); if ((flags & AuthenticatorDataFlags.UserPresent) == 0) { throw new Exception("user does not present"); } if (!rpidHash.SequenceEqual(CredentialUtility.Hash(Encoding.UTF8.GetBytes(rpid)))) { throw new Exception("RP ID Hash does not match"); } var publicKey = CBORObject.DecodeFromBytes(cred.PublicKey); var x = publicKey.MapGet(-2).GetByteString(); var y = publicKey.MapGet(-3).GetByteString(); var ecDsa = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, Q = new ECPoint { X = x, Y = y } }); var isValid = ecDsa.VerifyData(payload, rawSignature, HashAlgorithmName.SHA256); if (!isValid) { throw new Exception("invalid signature"); } if (cred.SignCounter >= counter) { throw new Exception("invalid signature counter"); } cred.SignCounter = counter; }
public ParseCTAP(byte[] cobrbyte) { try { cborobj = CBORObject.DecodeFromBytes(cobrbyte, CBOREncodeOptions.Default); // debug var json = cborobj.ToJSONString(); System.Diagnostics.Debug.WriteLine($"Recv: {json}"); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"CBOR DecordError:{ex.Message}"); } }
public void TestNestingDepth() { try { { using (var ms = new MemoryStream()) { for (var i = 0; i < 2000; ++i) { // Write beginning of indefinite-length array ms.WriteByte((byte)0x9f); } for (var i = 0; i < 2000; ++i) { // Write end of indefinite-length array ms.WriteByte((byte)0xff); } // Assert throwing CBOR exception for reaching maximum // nesting depth try { CBORObject.DecodeFromBytes(ms.ToArray()); Assert.Fail("Should have failed"); } catch (CBORException) { // NOTE: Intentionally empty } catch (Exception ex) { Assert.Fail(ex.ToString()); throw new InvalidOperationException(String.Empty, ex); } } } { using (var ms = new MemoryStream()) { for (var i = 0; i < 495; ++i) { // Write beginning of indefinite-length array ms.WriteByte((byte)0x9f); } for (var i = 0; i < 495; ++i) { // Write end of indefinite-length array ms.WriteByte((byte)0xff); } // Maximum nesting depth not reached, so shouldn't throw try { CBORObject.DecodeFromBytes(ms.ToArray()); } catch (Exception ex) { Assert.Fail(ex.ToString()); throw new InvalidOperationException(String.Empty, ex); } } } } catch (Exception ex) { throw new InvalidOperationException(ex.Message, ex); } }
public void DecodeFromCBORObject(CBORObject obj) { if (obj.Type != CBORType.Array) { throw new CoseException("Invalid Signer structure"); } if (obj.Count != 3) { throw new CoseException("Invalid Signer structure"); } if (obj[0].Type == CBORType.ByteString) { if (obj[0].GetByteString().Length == 0) { objProtected = CBORObject.NewMap(); rgbProtected = new byte[0]; } else { rgbProtected = obj[0].GetByteString(); objProtected = CBORObject.DecodeFromBytes(rgbProtected); if (objProtected.Count == 0) { rgbProtected = new byte[0]; } } } else { throw new CoseException("Invalid Signer structure"); } if (obj[1].Type == CBORType.Map) { objUnprotected = obj[1]; } else { throw new CoseException("Invalid Signer structure"); } if (obj[2].Type == CBORType.ByteString) { rgbSignature = obj[2].GetByteString(); } else { throw new CoseException("Invalid Signer structure"); } }
public void TestIncompleteCBORString() { byte[] bytes = { 0x65, 0x41, 0x41, 0x41, 0x41 }; try { CBORObject.DecodeFromBytes(bytes); Assert.Fail("Should have failed"); } catch (CBORException) { // NOTE: Intentionally empty } catch (Exception ex) { Assert.Fail(ex.ToString()); throw new InvalidOperationException(String.Empty, ex); } }