示例#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));
        }
示例#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"));
        }
示例#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"));
        }
示例#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);
        }
示例#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"));
        }
示例#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);
        }
示例#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"));
        }
示例#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());
        }
示例#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);
        }
示例#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"));
        }
示例#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);
 }
示例#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();
        }
示例#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;
        }
示例#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);
        }
示例#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);
        }
示例#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);
        }
示例#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);
            }
        }
示例#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));
        }
示例#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);
            }
示例#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);
        }
示例#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");
            }
        }
示例#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");
            }
        }
示例#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);
        }
示例#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());
        }
示例#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;
        }
示例#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);
        }
示例#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."));
        }
示例#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());
        }