示例#1
0
        protected byte[] toBeSigned(byte[] rgbContent, byte[] bodyAttributes)
        {
            CBORObject cborProtected = CBORObject.FromObject(new byte[0]);

            if ((ProtectedMap != null) && (ProtectedMap.Count > 0))
            {
                byte[] rgb = ProtectedMap.EncodeToBytes();
                cborProtected = CBORObject.FromObject(rgb);
            }

            if (rgbContent == null)
            {
                rgbContent = new byte[0];
            }

            CBORObject signObj = CBORObject.NewArray();

            signObj.Add(context);
            signObj.Add(bodyAttributes);
            signObj.Add(cborProtected);
            signObj.Add(ExternalData);
            signObj.Add(rgbContent);

#if FOR_EXAMPLES
            m_toBeSigned = signObj.EncodeToBytes();
#endif
            return(signObj.EncodeToBytes());
        }
示例#2
0
        /// <summary>
        /// Given the set of inputs, perform the crptographic operations that are needed
        /// to build a security context for a single sender and recipient.
        /// </summary>
        /// <param name="masterSecret">pre-shared key</param>
        /// <param name="entityId">name assigned to sender</param>
        /// <param name="masterSalt">salt value</param>
        /// <param name="algAEAD">encryption algorithm</param>
        /// <param name="algKeyAgree">key agreement algorithm</param>
        /// <returns></returns>
        private static EntityContext DeriveEntityContext(byte[] masterSecret, byte[] entityId, byte[] masterSalt = null, CBORObject algAEAD = null, CBORObject algKeyAgree = null)
        {
            EntityContext ctx = new EntityContext();

            ctx.Algorithm = algAEAD ?? AlgorithmValues.AES_CCM_64_64_128;
            ctx.Id        = entityId ?? throw new ArgumentNullException(nameof(entityId));
            if (algKeyAgree == null)
            {
                algKeyAgree = AlgorithmValues.ECDH_SS_HKDF_256;
            }

            ctx.ReplayWindow = new ReplayWindow(0, 64);

            CBORObject info = CBORObject.NewArray();

            // M00TODO - add the group id into this

            info.Add(entityId);                 // 0
            info.Add(ctx.Algorithm);            // 1
            info.Add("Key");                    // 2
            info.Add(128 / 8);                  // 3 in bytes


            IDigest sha256;

            if (algKeyAgree == null || algKeyAgree.Equals(AlgorithmValues.ECDH_SS_HKDF_256))
            {
                sha256 = new Sha256Digest();
            }
            else if (algKeyAgree.Equals(AlgorithmValues.ECDH_SS_HKDF_512))
            {
                sha256 = new Sha512Digest();
            }
            else
            {
                throw new ArgumentException("Unknown key agree algorithm");
            }

            IDerivationFunction hkdf = new HkdfBytesGenerator(sha256);

            hkdf.Init(new HkdfParameters(masterSecret, masterSalt, info.EncodeToBytes()));

            ctx.Key = new byte[128 / 8];
            hkdf.GenerateBytes(ctx.Key, 0, ctx.Key.Length);

            info[2] = CBORObject.FromObject("IV");
            info[3] = CBORObject.FromObject(56 / 8);
            hkdf.Init(new HkdfParameters(masterSecret, masterSalt, info.EncodeToBytes()));
            ctx.BaseIV = new byte[56 / 8];
            hkdf.GenerateBytes(ctx.BaseIV, 0, ctx.BaseIV.Length);

            return(ctx);
        }
示例#3
0
        public void PerformSignature()
        {
            CBORObject cborProtected = CBORObject.FromObject(new byte[0]);

            if ((objProtected != null) && (objProtected.Count > 0))
            {
                byte[] rgb = objProtected.EncodeToBytes();
                cborProtected = CBORObject.FromObject(rgb);
            }

            if (rgbSignature == null)
            {
                CBORObject signObj = CBORObject.NewArray();
                signObj.Add(context);
                signObj.Add(cborProtected);
                signObj.Add(externalData); // External AAD
                signObj.Add(rgbContent);

                rgbSignature = Sign(toBeSigned());

#if FOR_EXAMPLES
                m_toBeSigned = signObj.EncodeToBytes();
#endif
            }
        }
        public void decodeWrongBasis()
        {
            CBORObject obj = CBORObject.NewMap();

            byte[]  rgb = obj.EncodeToBytes();
            Message msg = Message.DecodeFromBytes(rgb, Tags.Enveloped);
        }
示例#5
0
        public AttestedCredentialData(byte[] attData, ref int offset)
        {
            Aaguid = AuthDataHelper.GetSizedByteArray(attData, ref offset, 16);
            if (null == Aaguid)
            {
                throw new Fido2VerificationException("Attested credential data is invalid");
            }
            CredentialID = AuthDataHelper.GetSizedByteArray(attData, ref offset);
            // Determining attested credential data's length, which is variable, involves determining credentialPublicKey’s beginning location given the preceding credentialId’s length, and then determining the credentialPublicKey’s length
            var ms = new System.IO.MemoryStream(attData, offset, attData.Length - offset);
            // CBORObject.Read: This method will read from the stream until the end of the CBOR object is reached or an error occurs, whichever happens first.
            CBORObject tmp = null;

            try
            {
                tmp = CBORObject.Read(ms);
            }
            catch (Exception)
            {
                throw new Fido2VerificationException("Failed to read credential public key from attested credential data");
            }
            var aCDLen = tmp.EncodeToBytes().Length;

            CredentialPublicKey = AuthDataHelper.GetSizedByteArray(attData, ref offset, (ushort)(aCDLen));
            if (null == CredentialID || null == CredentialPublicKey)
            {
                throw new Fido2VerificationException("Attested credential data is invalid");
            }
        }
示例#6
0
        private byte[] BuildContentBytes()
#endif
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(strContext);
            if (objProtected.Count > 0)
            {
                obj.Add(objProtected.EncodeToBytes());
            }
            else
            {
                obj.Add(CBORObject.FromObject(new byte[0]));
            }
            if (externalData != null)
            {
                obj.Add(CBORObject.FromObject(externalData));
            }
            else
            {
                obj.Add(CBORObject.FromObject(new byte[0]));
            }
            obj.Add(rgbContent);

            return(obj.EncodeToBytes());
        }
示例#7
0
 public static void AssertRoundTrip(CBORObject o)
 {
     CBORObject o2 = FromBytesTestAB(o.EncodeToBytes());
       TestCommon.CompareTestEqual(o, o2);
       TestNumber(o);
       TestCommon.AssertEqualsHashCode(o, o2);
 }
示例#8
0
        private byte[] BuildContentBytes()
#endif
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(_strContext);
            if (ProtectedBytes == null)
            {
                if (ProtectedMap.Count > 0)
                {
                    ProtectedBytes = ProtectedMap.EncodeToBytes();
                }
                else
                {
                    ProtectedBytes = new byte[0];
                }
            }
            obj.Add(ProtectedBytes);
            if (ExternalData != null)
            {
                obj.Add(CBORObject.FromObject(ExternalData));
            }
            else
            {
                obj.Add(CBORObject.FromObject(new byte[0]));
            }
            obj.Add(rgbContent);

            return(obj.EncodeToBytes());
        }
        /**
         * Verifies the signature of the COSE_Sign1 object.
         * <p>
         * Note: This method only verifies the signature. Not the payload.
         * </p>
         *
         * @param publicKey
         *          the key to use when verifying the signature
         * @throws SignatureException
         *           for signature verification errors
         */
        public void VerifySignature(byte[] publicKey)
        {
            if (Signature == null)
            {
                throw new Exception("Object is not signed");
            }

            CBORObject obj = CBORObject.NewArray();

            obj.Add(ContextString);
            obj.Add(ProtectedAttributesEncoding);
            obj.Add(ExternalData);
            if (Content != null)
            {
                obj.Add(Content);
            }
            else
            {
                obj.Add(null);
            }

            byte[] signedData = obj.EncodeToBytes();

            // First find out which algorithm to use by searching for the algorithm ID in the protected attributes.
            //
            CBORObject registeredAlgorithm = ProtectedAttributes[HeaderParameterKey.ALG];

            if (registeredAlgorithm == null)
            {
                throw new Exception("No algorithm ID stored in protected attributes - cannot sign");
            }

            byte[] signatureToVerify = Signature;

            // For ECDSA, convert the signature according to section 8.1 of RFC8152.
            //
            if (registeredAlgorithm == SignatureAlgorithm.ES256 ||
                registeredAlgorithm == SignatureAlgorithm.ES384 ||
                registeredAlgorithm == SignatureAlgorithm.ES512)
            {
                signatureToVerify = ConvertToDer(Signature);
            }


            // Verify using the public key
            var pubkey = PublicKeyFactory.CreateKey(publicKey);

            var verifier = SignerUtilities.GetSigner(SignatureAlgorithm.GetAlgorithmName(registeredAlgorithm));

            verifier.Init(false, pubkey);
            verifier.BlockUpdate(signedData, 0, signedData.Length);
            var result = verifier.VerifySignature(signatureToVerify);

            if (!result)
            {
                throw new CertificateValidationException("Signature did not verify correctly");
            }
            Console.WriteLine("result: " + result);
        }
示例#10
0
        public static void AssertRoundTrip(CBORObject o)
        {
            CBORObject o2 = FromBytesTestAB(o.EncodeToBytes());

            TestCommon.CompareTestEqual(o, o2);
            TestNumber(o);
            TestCommon.AssertEqualsHashCode(o, o2);
        }
        public void decodeWrongCount()
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(CBORObject.False);

            byte[] rgb = obj.EncodeToBytes();
            Message.DecodeFromBytes(rgb, Tags.Enveloped);
        }
示例#12
0
        public void macDecodeWrongBasis()
        {
            CBORObject obj = CBORObject.NewMap();

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

            Assert.AreEqual(e.Message, ("Message is not a COSE security message."));
        }
示例#13
0
        public void decodeBadUnprotected()
        {
            CBORObject obj = CBORObject.NewArray();

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

            byte[] rgb = obj.EncodeToBytes();
            Message.DecodeFromBytes(rgb, Tags.Encrypted);
        }
示例#14
0
        public byte[] EncodeToBytes()
        {
            CBORObject m_array = CBORObject.NewArray();

            foreach (Key k in m_keyList)
            {
                m_array.Add(k.AsCBOR());
            }

            return(m_array.EncodeToBytes());
        }
示例#15
0
        public static void AssertJSONSer(CBORObject o, String s)
        {
            if (!s.Equals(o.ToJSONString(), StringComparison.Ordinal))
            {
                Assert.AreEqual(s, o.ToJSONString(), "o is not equal to s");
            }
            // Test round-tripping
            CBORObject o2 = FromBytesTestAB(o.EncodeToBytes());

            if (!s.Equals(o2.ToJSONString(), StringComparison.Ordinal))
            {
                string msg = "o2 is not equal to s:\no = " +
                             TestCommon.ToByteArrayString(o.EncodeToBytes()) +
                             "\no2 = " + TestCommon.ToByteArrayString(o2.EncodeToBytes()) +
                             "\no2string = " + o2.ToString();
                Assert.AreEqual(s, o2.ToJSONString(), msg);
            }
            TestNumber(o);
            TestCommon.AssertEqualsHashCode(o, o2);
        }
示例#16
0
#pragma warning restore CS0618

        public static byte[] CheckEncodeToBytes(CBORObject o)
        {
            byte[] bytes = o.EncodeToBytes();
            if (bytes.Length != o.CalcEncodedSize())
            {
                string msg = "encoded size doesn't match:\no = " +
                             TestCommon.ToByteArrayString(bytes) + "\nostring = " + o.ToString();
                Assert.AreEqual(bytes.Length, o.CalcEncodedSize(), msg);
            }
            return(bytes);
        }
        public void decodeBadProtected2()
        {
            CBORObject obj = CBORObject.NewArray();

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

            byte[] rgb = obj.EncodeToBytes();
            Message.DecodeFromBytes(rgb, Tags.Enveloped);
        }
示例#18
0
        static void RunSetPayload(string[] cmds)
        {
            if (cmds.Length != 2)
            {
                Console.WriteLine("Incorrect command");
                return;
            }

            CBORObject cbor = CBORDiagnostics.Parse(cmds[1]);

            Body = cbor.EncodeToBytes();
        }
        public void decodeBadRecipients()
        {
            CBORObject obj = CBORObject.NewArray();

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

            byte[] rgb = obj.EncodeToBytes();
            Message.DecodeFromBytes(rgb, Tags.Enveloped);
        }
示例#20
0
        public void macDecodeWrongCount()
        {
            CBORObject obj = CBORObject.NewArray();

            obj.Add(CBORObject.False);

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

            Assert.AreEqual(e.Message, ("Invalid MAC structure"));
        }
示例#21
0
 public static void AssertSer(CBORObject o, String s)
 {
     if (!s.Equals(o.ToString())) {
     Assert.AreEqual(s, o.ToString(), "o is not equal to s");
       }
       // Test round-tripping
       CBORObject o2 = FromBytesTestAB(o.EncodeToBytes());
       if (!s.Equals(o2.ToString())) {
     Assert.AreEqual(s, o2.ToString(), "o2 is not equal to s");
       }
       TestNumber(o);
       TestCommon.AssertEqualsHashCode(o, o2);
 }
示例#22
0
        private static void AddTlsCwt(string[] commands)
        {
            if (commands.Length != 4)
            {
                Console.Write($"Incorrect number of arguments: {commands.Length}");
                return;
            }

            CBORObject cbor = CBORDiagnostics.Parse(commands[2]);
            CWT        cwt  = CWT.Decode(cbor.EncodeToBytes(), CwtRootKeys, CwtRootKeys);

            cbor = CBORDiagnostics.Parse(commands[3]);
            _TlsKeys.Add(commands[1], new TlsKeyPair(cwt, new OneKey(cbor)));
        }
示例#23
0
        private byte[] toBeSigned()
        {
            CBORObject cborProtected = CBORObject.FromObject(new byte[0]);

            if ((objProtected != null) && (objProtected.Count > 0))
            {
                byte[] rgb = objProtected.EncodeToBytes();
                cborProtected = CBORObject.FromObject(rgb);
            }

            CBORObject signObj = CBORObject.NewArray();

            signObj.Add(context);
            signObj.Add(cborProtected);
            signObj.Add(externalData); // External AAD
            signObj.Add(rgbContent);

#if FOR_EXAMPLES
            m_toBeSigned = signObj.EncodeToBytes();
#endif

            return(signObj.EncodeToBytes());
        }
示例#24
0
        public void EncryptDecodeBadTag()
        {
            CBORObject obj = CBORObject.NewArray();

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

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

            Assert.AreEqual(e.Message, ("Invalid Encrypt0 structure"));
        }
示例#25
0
        public byte[] CreateMessage3()
        {
            CBORObject msg = CBORObject.NewArray();

            if (_fSymmetricSecret)
            {
                msg.Add(6);
            }
            else
            {
                msg.Add(3);
            }
            msg.Add(_SessionId[1]);

            byte[] aad_3 = ConcatenateAndHash(new byte[2][] { _LastMessageAuthenticator, msg.EncodeToBytes() }, _MessageDigest);

            byte[] signBody = new byte[0];
            if (!_fSymmetricSecret)
            {
                Sign1Message sign1 = new Sign1Message(false, false);
                sign1.SetContent(aad_3);
                sign1.AddAttribute(HeaderKeys.Algorithm, _algSign, Attributes.DO_NOT_SEND);
                sign1.AddAttribute(HeaderKeys.KeyId, _SigningKey[CoseKeyKeys.KeyIdentifier], Attributes.UNPROTECTED);
                sign1.Sign(_SigningKey);

                CBORObject obj = CBORObject.NewArray();
                obj.Add(sign1.EncodeToBytes());

                signBody = obj.EncodeToBytes();
            }

            byte[][] encKeys = _DeriveKeys(_Keys, _SecretSalt, aad_3, _algAEAD);

            Encrypt0Message enc = new Encrypt0Message(false);

            enc.SetContent(signBody);
            enc.SetExternalData(aad_3);
            enc.AddAttribute(HeaderKeys.Algorithm, _algAEAD, Attributes.DO_NOT_SEND);
            enc.AddAttribute(HeaderKeys.IV, CBORObject.FromObject(encKeys[1]), Attributes.DO_NOT_SEND);
            enc.Encrypt(encKeys[0]);

            msg.Add(enc.EncodeToBytes());

            byte[] msgOut = msg.EncodeToBytes();

            _LastMessageAuthenticator = ConcatenateAndHash(new byte[2][] { _LastMessageAuthenticator, msgOut }, _MessageDigest);

            return(msgOut);
        }
示例#26
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"));
        }
示例#27
0
        public async Task <bool> SwatoothKeyStore(EncoderSettings settings, CBORObject obj)
        {
            if (obj != null && settings != null)
            {
                var res = await _key.InsertOneAsync(new KeyMaintainer()
                {
                    certficate  = Convert.ToBase64String(obj.EncodeToBytes()),
                    keysettings = Newtonsoft.Json.JsonConvert.SerializeObject(settings),
                    uname       = obj["Name"].AsString(),
                    CreatedAt   = DateTime.Now
                });

                return(res);
            }
            return(false);
        }
示例#28
0
        public static void AssertSer(CBORObject o, String s)
        {
            if (!s.Equals(o.ToString()))
            {
                Assert.AreEqual(s, o.ToString(), "o is not equal to s");
            }
            // Test round-tripping
            CBORObject o2 = FromBytesTestAB(o.EncodeToBytes());

            if (!s.Equals(o2.ToString()))
            {
                Assert.AreEqual(s, o2.ToString(), "o2 is not equal to s");
            }
            TestNumber(o);
            TestCommon.AssertEqualsHashCode(o, o2);
        }
示例#29
0
        public static ushort GetCBORMapLength(byte[] buffer, int index, int count)
        {
            var ms = new System.IO.MemoryStream(buffer, index, count);
            // CBORObject.Read: This method will read from the stream until the end of the CBOR object is reached or an error occurs, whichever happens first.
            CBORObject tmp = null;

            try
            {
                tmp = CBORObject.Read(ms);
            }
            catch (Exception)
            {
                throw new Fido2VerificationException("Failed to read CBOR map");
            }
            return((ushort)tmp.EncodeToBytes().Length);
        }
示例#30
0
        public void signDecodeBadRecipients()
        {
            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.Sign));

            Assert.AreEqual(e.Message, ("Invalid SignMessage structure"));
        }
示例#31
0
        public static byte[] SerializeCbor(IResource root, IEnumerable <string> queries)
        {
            CBORObject linkFormat = CBORObject.NewArray();

            List <string> queryList = null;

            if (queries != null)
            {
                queryList = queries.ToList();
            }

            foreach (IResource child in root.Children)
            {
                SerializeTree(child, queryList, linkFormat, _CborAttributeKeys);
            }

            return(linkFormat.EncodeToBytes());
        }
示例#32
0
        public byte[] CreateMessage1()
        {
            CBORObject msg = CBORObject.NewArray();

            if (_fSymmetricSecret)
            {
                msg.Add(4);
            }
            else
            {
                msg.Add(1);                                 // Msg Type
            }

            msg.Add(_SessionId[0]);
            msg.Add(_Nonce[0]);
            msg.Add(_Keys[0].PublicKey().AsCBOR());

            CBORObject obj = CBORObject.NewArray();         // Key Agree algorithms

            obj.Add(AlgorithmValues.ECDH_SS_HKDF_256);
            msg.Add(obj);

            obj = CBORObject.NewArray();
            obj.Add(AlgorithmValues.AES_CCM_64_64_128);     // AEAD algorithms
            msg.Add(obj);

            if (_fSymmetricSecret)
            {
                msg.Add(_SharedSecret[CoseKeyKeys.KeyIdentifier]);
            }
            else
            {
                obj = CBORObject.NewArray();                // SIG verify algorithms
                obj.Add(AlgorithmValuesInt.ECDSA_256);
                obj.Add(AlgorithmValues.EdDSA);
                msg.Add(obj);

                msg.Add(obj);                               // SIG generate algorithms
            }

            _Messages[0] = msg.EncodeToBytes();         // message_1
            _LastMessageAuthenticator = _Messages[0];
            return(_Messages[0]);
        }
示例#33
0
 private static string ObjectMessage(CBORObject obj)
 {
     return new System.Text.StringBuilder()
     .Append("CBORObject.DecodeFromBytes(")
        .Append(TestCommon.ToByteArrayString(obj.EncodeToBytes()))
        .Append("); /").Append("/ ").Append(obj.ToJSONString()).ToString();
 }