Exemplo n.º 1
0
        public void TestRoundTrip4()
        {
            Encrypt0Message msg = new Encrypt0Message();

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, Attributes.PROTECTED);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attributes.PROTECTED);
            msg.SetContent(rgbContent);
            msg.Encrypt(rgbKey128);
            CBORObject rgbMsg = msg.EncodeToCBORObject();

            msg = (Encrypt0Message)Message.DecodeFromCBOR(rgbMsg);
            byte[] contentNew = msg.Decrypt(rgbKey128);

            CollectionAssert.AreEqual(rgbContent, (contentNew));
        }
Exemplo n.º 2
0
        public void macDecodeBadRecipients()
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(CBORObject.FromObject(CBORObject.NewArray()).EncodeToBytes());
            obj.Add(CBORObject.NewMap());
            obj.Add(new byte[0]);
            obj.Add(CBORObject.False);

            byte[]        rgb = obj.EncodeToBytes();
            CoseException e   = Assert.ThrowsException <CoseException>(() =>
                                                                       Message.DecodeFromBytes(rgb, Tags.MAC0));

            Assert.AreEqual(e.Message, ("Invalid MAC0 structure"));
        }
Exemplo n.º 3
0
        public void EncryptDecodeBadContent()
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(CBORObject.FromObject(CBORObject.NewArray()).EncodeToBytes());
            obj.Add(CBORObject.NewMap());
            obj.Add(CBORObject.False);
            obj.Add(CBORObject.False);

            byte[]        rgb = obj.EncodeToBytes();
            CoseException e   = Assert.ThrowsException <CoseException>(() =>
                                                                       Message.DecodeFromBytes(rgb, Tags.Encrypt));

            Assert.AreEqual(e.Message, ("Invalid Encrypt structure"));
        }
Exemplo n.º 4
0
        public void TestAppleInvalidNonce()
        {
            var trustPath = validX5cStrings
                            .Select(x => new X509Certificate2(Convert.FromBase64String(x)))
                            .ToArray();

            var X5c = CBORObject.NewArray()
                      .Add(CBORObject.FromObject(trustPath[0].RawData))
                      .Add(CBORObject.FromObject(trustPath[1].RawData));

            _attestationObject["attStmt"].Set("x5c", X5c);
            var ex = Assert.ThrowsAsync <Fido2VerificationException>(() => MakeAttestationResponse());

            Assert.Equal("Mismatch between nonce and credCert attestation extension in Apple attestation", ex.Result.Message);
        }
Exemplo n.º 5
0
        public void decodeBadUnprotected()
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(CBORObject.FromObject(CBORObject.NewArray()).EncodeToBytes());
            obj.Add(CBORObject.False);
            obj.Add(CBORObject.False);
            obj.Add(CBORObject.False);

            byte[]        rgb = obj.EncodeToBytes();
            CoseException e   = Assert.ThrowsException <CoseException>(() =>
                                                                       Message.DecodeFromBytes(rgb, Tags.Sign1));

            Assert.AreEqual(e.Message, ("Invalid Sign1 structure"));
        }
Exemplo n.º 6
0
        public void TestEquivalentInfinities()
        {
            CBORObject co, co2;

            co  = CBORObject.FromObject(CBORTestCommon.DecPosInf);
            co2 = CBORObject.FromObject(Double.PositiveInfinity);
            TestCommon.CompareTestEqual(co, co2);
            co = CBORObject.NewMap().Add(
                CBORTestCommon.DecPosInf,
                CBORObject.Undefined);
            co2 = CBORObject.NewMap().Add(
                Double.PositiveInfinity,
                CBORObject.Undefined);
            TestCommon.CompareTestEqual(co, co2);
        }
Exemplo n.º 7
0
        public void testDecodeUnknown()
        {
            Encrypt0Message msg = new Encrypt0Message(false, true);

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, Attributes.PROTECTED);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attributes.PROTECTED);
            msg.SetContent(rgbContent);
            msg.Encrypt(rgbKey128);
            byte[] rgbMsg = msg.EncodeToBytes();

            CoseException e = Assert.ThrowsException <CoseException>(() =>
                                                                     msg = (Encrypt0Message)Message.DecodeFromBytes(rgbMsg, Tags.Unknown));

            Assert.AreEqual(e.Message, ("Message was not tagged and no default tagging option given"));
        }
Exemplo n.º 8
0
        public void LookupBinary()
        {
            byte[] bytes1 = new byte[] { 2, 4, 6, 8, 10, 12, 14, 16 };
            byte[] bytes2 = new byte[] { 1, 3, 5, 7, 9, 11, 13, 15 };

            CBORObject result = _dictionary.Lookup(CBORObject.FromObject(bytes1), true);

            Assert.AreEqual(CBORType.ByteString, result.Type);

            result = _dictionary.Lookup(CBORObject.FromObject(bytes2), true);
            Assert.AreEqual(CBORType.Integer, result.Type);
            Assert.IsTrue(result.IsTagged);
            Assert.IsTrue(result.HasOneTag(CoralDictionary.DictionaryTag));
            Assert.AreEqual(6, result.UntagOne().AsInt32());
        }
Exemplo n.º 9
0
        public void roundTrip()
        {
            Encrypt0Message msg = new Encrypt0Message();

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, Attributes.PROTECTED);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attributes.UNPROTECTED);
            msg.SetContent(strContent);
            msg.Encrypt(rgbKey128);
            byte[] rgbMsg = msg.EncodeToBytes();

            msg = (Encrypt0Message)Message.DecodeFromBytes(rgbMsg);
            msg.Decrypt(rgbKey128);

            Assert.AreEqual <string>(msg.GetContentAsString(), strContent);
        }
Exemplo n.º 10
0
        public void signerDecodeBadUnprotected()
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(CBORObject.FromObject(CBORObject.NewArray()).EncodeToBytes());
            obj.Add(CBORObject.False);
            obj.Add(CBORObject.False);


            Signer        sig = new Signer();
            CoseException e   = Assert.ThrowsException <CoseException>(() =>
                                                                       sig.DecodeFromCBORObject(obj));

            Assert.AreEqual(e.Message, ("Invalid Signer structure"));
        }
Exemplo n.º 11
0
 internal RSA CreateRsa()
 {
     if (_type == COSE.KeyType.RSA)
     {
         var rsa = RSA.Create();
         rsa.ImportParameters(
             new RSAParameters()
         {
             Modulus  = _cpk[CBORObject.FromObject(COSE.KeyTypeParameter.N)].GetByteString(),
             Exponent = _cpk[CBORObject.FromObject(COSE.KeyTypeParameter.E)].GetByteString()
         }
             );
         return(rsa);
     }
     return(null);
 }
Exemplo n.º 12
0
        public static void OneTimeSetup(TestContext ctx)
        {
            PskOne = new OneKey();
            PskOne.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskOne.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(PskOneName));
            PskOne.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("abcDEFghiJKL")));

            PskTwo = new OneKey();
            PskTwo.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskTwo.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(PskTwoName));
            PskTwo.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("12345678091234")));

            UserKeys = new KeySet();
            // UserKeys.AddKey(PskOne);
            // UserKeys.AddKey(PskTwo);
        }
        public void ConnectPSK(string GatewaySecret)
        {
            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(GatewaySecret)));

            DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);

            (Implementation as CoapImplementation)._coapClient = new CoapClient(new Uri($"coaps://{_gatewayIp}"))
            {
                EndPoint = ep
            };

            ep.Start();
        }
Exemplo n.º 14
0
        public void Connect()
        {
            OneKey userKey = new OneKey();

            userKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            userKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(PreSharedKey)));

            DTLSClientEndPoint ep = new DTLSClientEndPoint(userKey);
            CoapClient         cc = new CoapClient(new Uri($"coaps://{GatewayIp}"))
            {
                EndPoint = ep
            };

            ep.Start();
            Client = cc;
        }
Exemplo n.º 15
0
        public IGateway Connect(string psk)
        {
            _logger.LogInformation($"Connecting to {_ipAddress} as \"{_clientIdentity}\" with PSK \"{psk}\"");

            var authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(psk)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(_clientIdentity)));

            var clientEndPoint = new DTLSClientEndPoint(authKey);

            clientEndPoint.Start();

            return(new Gateway(clientEndPoint, new Uri($"coaps://{_ipAddress}"), _logger));
        }
        public void encryptNoEmitContent()
        {
            EnvelopedMessage msg = new EnvelopedMessage(true, false);

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, true);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), false);
            msg.SetContent(strContent);
            Recipient r = new Recipient(key128, AlgorithmValues.Direct);

            msg.AddRecipient(r);
            msg.Encrypt();
            CBORObject cn = msg.EncodeToCBORObject();


            Assert.IsTrue(cn[2].IsNull);
        }
Exemplo n.º 17
0
        public void encryptNoTag()
        {
            EncryptMessage msg = new EncryptMessage(false, true);

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, Attributes.PROTECTED);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attributes.UNPROTECTED);
            msg.SetContent(strContent);
            Recipient r = new Recipient(key128, AlgorithmValues.Direct);

            msg.AddRecipient(r);
            msg.Encrypt();
            CBORObject cn = msg.EncodeToCBORObject();


            Assert.IsFalse(cn.IsTagged);
        }
Exemplo n.º 18
0
        private static void SerializeAttributeInCoral(string name, List <string> values, CoralBody coral,
                                                      Dictionary <string, CBORObject> dictionary)
        {
            bool       useSpace = SpaceSeparatedValueAttributes.Contains(name);
            CBORObject result;

            string nameX = CoralsKeys[name];

            if (useSpace && values.Count > 1)
            {
                StringBuilder sb = new StringBuilder();

                foreach (string value in values)
                {
                    sb.Append(value);
                    sb.Append(" ");
                }

                sb.Length = sb.Length - 1;

                result = CBORObject.FromObject(sb.ToString());
            }
            else if (values.Count == 1)
            {
                string value = values.First();
                result = string.IsNullOrEmpty(value) ? CBORObject.True : CBORObject.FromObject(values.First());
            }
            else
            {
                result = CBORObject.NewArray();
                foreach (string value in values)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        result.Add(CBORObject.True);
                    }
                    else
                    {
                        result.Add(value);
                    }
                }
            }

            CoralLink link = new CoralLink(nameX, result);

            coral.Add(link);
        }
Exemplo n.º 19
0
        public string GeneratePsk(string gatewaySecret)
        {
            try
            {
                _logger.LogInformation($"Connecting to {_ipAddress} as \"{_clientIdentity}\" to generate new PSK");

                var authKey = new OneKey();
                authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(gatewaySecret)));
                authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));
                using (var clientEndPoint = new DTLSClientEndPoint(authKey))
                {
                    clientEndPoint.Start();

                    var authRequest = new AuthRequest {
                        Identity = _clientIdentity
                    };

                    var request = new Request(Method.POST)
                    {
                        EndPoint   = clientEndPoint,
                        AckTimeout = 5000
                    };

                    request.SetUri($"coaps://{_ipAddress}/{(int)RequestRoot.Gateway}/{(int)TradfriAttribute.Auth}/");
                    string json = Json.Serialize(authRequest);
                    request.SetPayload(json);
                    request.Send();

                    Response response = request.WaitForResponse(5000);
                    if (response == null)
                    {
                        throw new TradfriException("No response from gateway");
                    }

                    AuthResponse authResponse = Json.Deserialize <AuthResponse>(response.PayloadString);

                    _logger.LogInformation($"PSK generated: \"{authResponse.Psk}\"");

                    return(authResponse.Psk);
                }
            }
            catch (Exception exception)
            {
                throw new TradfriException("Failed during authentication.", exception);
            }
        }
Exemplo n.º 20
0
        public CBORObject Lookup(string value, bool isIntLegal)
        {
            foreach (KeyValuePair <int, object> o in _dictionary)
            {
                if (value.Equals(o.Value))
                {
                    if (isIntLegal)
                    {
                        return(CBORObject.FromObjectAndTag(o.Key, DictionaryTag));
                    }

                    return(CBORObject.FromObject(o.Key));
                }
            }

            return(CBORObject.FromObject(value));
        }
Exemplo n.º 21
0
            public async Task EncodeAsync <T>(T obj, CancellationToken cancellationToken = default(CancellationToken))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                if (_codec._multicodec)
                {
                    await _stream.WriteAsync(_codec.Header, 0, _codec.Header.Length, cancellationToken);
                }

                var cbor = CBORObject.FromObject(obj);

                cbor.WriteTo(_stream);
                await _stream.FlushAsync(cancellationToken);
            }
Exemplo n.º 22
0
        public void roundTripDetached()
        {
            Encrypt0Message msg = new Encrypt0Message(true, false);

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, Attributes.PROTECTED);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attributes.UNPROTECTED);
            msg.SetContent(strContent);
            msg.Encrypt(rgbKey128);

            byte[] content = msg.GetEncryptedContent();

            byte[] rgb = msg.EncodeToBytes();

            msg = (Encrypt0Message)Message.DecodeFromBytes(rgb);
            msg.SetEncryptedContent(content);
            msg.Decrypt(rgbKey128);
        }
Exemplo n.º 23
0
        public void TestAddAttribute_2()
        {
            CBORObject label = CBORObject.FromObject(1);
            CBORObject value = CBORObject.FromObject(2);

            int where = 0;
            Attributes instance = new Attributes();

            try
            {
                instance.AddAttribute(label, value, where);
            }
            catch (JoseException e)
            {
                Assert.AreEqual(e.Message, "Invalid attribute location given");
            }
        }
Exemplo n.º 24
0
        public void TestAddAttribute_1()
        {
            CBORObject label = CBORObject.FromObject(new byte[1]);
            CBORObject value = null;

            int where = Attributes.PROTECTED;
            Attributes instance = new Attributes();

            try
            {
                instance.AddAttribute(label, value, where);
            }
            catch (JoseException e)
            {
                Assert.AreEqual(e.Message, "Labels must be integers or strings");
            }
        }
Exemplo n.º 25
0
        public void nullKeyForDecrypt()
        {
            Encrypt0Message msg = new Encrypt0Message(true, true);

            //        thrown.expect(CoseException.class);
            //        thrown.expectMessage("No Encrypted Content Specified");

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, Attributes.PROTECTED);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attributes.UNPROTECTED);
            msg.SetContent(strContent);
            msg.Encrypt(rgbKey128);

            byte[] rgb = msg.EncodeToBytes();

            msg = (Encrypt0Message)Message.DecodeFromBytes(rgb);
            msg.Decrypt(null);
        }
Exemplo n.º 26
0
        public void LookupString()
        {
            CBORObject result = _dictionary.Lookup("http://www.iana.org/assignments/relation/item>", false);

            Assert.AreEqual(CBORType.Integer, result.Type);
            Assert.AreEqual(1, result.AsInt32());

            result = _dictionary.Lookup(CBORObject.FromObject("http://www.iana.org/assignments/relation/item>"), false);
            Assert.AreEqual(CBORType.Integer, result.Type);
            Assert.AreEqual(1, result.AsInt32());

            result = _dictionary.Lookup(CBORObject.FromObject("http://www.iana.org/assignments/relation/item>"), true);
            Assert.AreEqual(CBORType.Integer, result.Type);
            Assert.IsTrue(result.IsTagged);
            Assert.IsTrue(result.HasOneTag(CoralDictionary.DictionaryTag));
            Assert.AreEqual(1, result.Untag().AsInt32());
        }
Exemplo n.º 27
0
        public void ConnectAppKey(string appKey, string applicationName)
        {
            OneKey authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(appKey)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(applicationName)));

            DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);
            CoapClient         cc = new CoapClient(new Uri($"coaps://{_gatewayIp}"))
            {
                EndPoint = ep
            };

            ep.Start();

            _coapClient = cc;
        }
Exemplo n.º 28
0
        public CBORObject Lookup(CBORObject value)
        {
            foreach (KeyValuePair <int, string> o in _dictionary)
            {
                if (value.Equals(CBORObject.FromObject(o.Value)))
                {
                    CBORObject newValue = CBORObject.FromObject(o.Key);
                    if (value.Type == CBORType.Number)
                    {
                        newValue = CBORObject.FromObjectAndTag(newValue, DictionaryTag);
                    }

                    return(newValue);
                }
            }

            return(value);
        }
Exemplo n.º 29
0
        public void NoContentForDecrypt()
        {
            Encrypt0Message msg = new Encrypt0Message(true, false);


            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.AES_GCM_128, Attributes.PROTECTED);
            msg.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attributes.UNPROTECTED);
            msg.SetContent(rgbContent);
            msg.Encrypt(rgbKey128);

            byte[] rgb = msg.EncodeToBytes();

            msg = (Encrypt0Message)Message.DecodeFromBytes(rgb);
            CoseException e = Assert.ThrowsException <CoseException>(() =>
                                                                     msg.Decrypt(rgbKey128));

            Assert.AreEqual(e.Message, ("No Encrypted Content Specified."));
        }
Exemplo n.º 30
0
        public void LookupInteger()
        {
            CBORObject result = _dictionary.Lookup(CBORObject.FromObject(5), true);

            Assert.AreEqual(CBORType.Integer, result.Type);
            Assert.IsFalse(result.IsTagged);
            Assert.AreEqual(5, result.AsInt32());

            result = _dictionary.Lookup(CBORObject.FromObject(5), false);
            Assert.AreEqual(CBORType.Integer, result.Type);
            Assert.IsFalse(result.IsTagged);
            Assert.AreEqual(5, result.AsInt32());

            result = _dictionary.Lookup(CBORObject.FromObject(-5), true);
            Assert.AreEqual(CBORType.Integer, result.Type);
            Assert.IsFalse(result.IsTagged);
            Assert.AreEqual(-5, result.AsInt32());
        }