public void TestSharedSecret() { Request req; Uri uriHello = new Uri("coap://localhost:" + _serverPort + "/hello"); Uri uri = new Uri("coap://localhost:" + _serverPort + "/" + "edhoc"); CoapClient clientHello = new CoapClient(uriHello); CoapClient client = new CoapClient(uri); // Try and get hello -- should fail because no security setup. CoAP.Response resp = clientHello.Get(); Assert.AreEqual(CoAP.StatusCode.Unauthorized, resp.StatusCode); // Create and send message #1 for PSK EDHOC.EdhocInitiator init = new EdhocInitiator(psk); byte[] msg = init.CreateMessage1(); req = new Request(Method.POST); req.Payload = msg; resp = client.Send(req); Assert.AreEqual(CoAP.StatusCode.Changed, resp.StatusCode); // Process response message KeySet ks = new KeySet(); ks.AddKey(serverSignKey); init.ParseMessage2(resp.Payload, ks); // Post new message msg = init.CreateMessage3(); req = new Request(Method.POST); req.Payload = msg; resp = client.Send(req); Assert.AreEqual(StatusCode.Changed, resp.StatusCode); // Setup my security context. OSCOAP.SecurityContext ctx = init.CreateSecurityContext(); req = new Request(Method.GET); req.URI = uriHello; req.OscoapContext = ctx; resp = clientHello.Send(req); Assert.AreEqual(StatusCode.Content, resp.StatusCode); }
protected override void DoPost(CoapExchange exchange) { byte[] body = exchange.Request.Payload; EdhocResponder edhoc; try { switch (body[1] & 0xf) { case 1: edhoc = EdhocResponder.ParseMessage1(body); edhoc.SigningKey = _signKey; body = edhoc.CreateMessage2(); exchange.Respond(CoAP.StatusCode.Changed, body); break; case 4: edhoc = EdhocResponder.ParseMessage1(body); OneKey y = null; foreach (OneKey x in _allKeys) { if (x.ContainsName(CoseKeyKeys.KeyIdentifier)) { if (x.HasKid(edhoc.KeyIdentifier)) { if (y != null) { exchange.Respond(CoAP.StatusCode.BadRequest); return; } y = new OneKey(x.AsCBOR()); } } } if (y == null) { exchange.Respond(CoAP.StatusCode.BadRequest); return; } if (!y[CoseKeyKeys.KeyType].Equals(GeneralValues.KeyType_Octet)) { exchange.Respond(CoAP.StatusCode.BadRequest); return; } edhoc.SharedSecret = y; body = edhoc.CreateMessage2(); exchange.Respond(CoAP.StatusCode.Changed, body); break; case 3: edhoc = EdhocResponder.ParseMessage3(body, _allKeys); exchange.Respond(StatusCode.Changed); OSCOAP.SecurityContext ctx = edhoc.CreateSecurityContext(); OSCOAP.SecurityContextSet.AllContexts.Add(ctx); break; case 6: edhoc = EdhocResponder.ParseMessage3(body, _allKeys); exchange.Respond(CoAP.StatusCode.Changed); OSCOAP.SecurityContext ctx2 = edhoc.CreateSecurityContext(); OSCOAP.SecurityContextSet.AllContexts.Add(ctx2); break; default: exchange.Respond(CoAP.StatusCode.BadRequest); break; } } catch (Exception e) { CBORObject obj = CBORObject.NewArray(); obj.Add(0); obj.Add(e.ToString()); exchange.Respond(CoAP.StatusCode.Content, obj.EncodeToBytes()); } }