Пример #1
0
 public DTLSSession(IPEndPoint ipEndPoint, EventHandler <DataReceivedEventArgs> dataReceived, OneKey userKey)
 {
     _ipEndPoint   = ipEndPoint;
     _dataReceived = dataReceived;
     _userKey      = userKey;
     _transport    = new OurTransport(ipEndPoint);
 }
Пример #2
0
        public TradFriAuth GeneratePSK(string GatewaySecret, string applicationName)
        {
            Response resp = new Response(StatusCode.Valid);

            try
            {
                OneKey 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")));
                DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);
                ep.Start();

                Request r = new Request(Method.POST);
                r.SetUri($"coaps://{GatewayIp}" + $"/{(int)TradFriConstRoot.Gateway}/{(int)TradFriConstAttr.Auth}/");
                r.EndPoint   = ep;
                r.AckTimeout = 5000;
                r.SetPayload($@"{{""{(int)TradFriConstAttr.Identity}"":""{applicationName}""}}");

                r.Send();
                resp = r.WaitForResponse(5000);

                return(JsonConvert.DeserializeObject <TradFriAuth>(resp.PayloadString));
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);

                var content = JsonConvert.DeserializeObject <dynamic>(resp.PayloadString);
                return(new TradFriAuth());
            }
        }
Пример #3
0
 public DTLSClientChannel(CWT cwt, OneKey userKey, KeySet cwtTrustKeys, int port)
 {
     _port          = port;
     _userKey       = userKey;
     _userCwt       = cwt;
     CwtTrustKeySet = cwtTrustKeys;
 }
Пример #4
0
            public void GetCwtKey(CwtPublicKey rpk)
            {
                try {
                    CWT cwt = CWT.Decode(rpk.EncodedCwt(), CwtTrustKeySet, CwtTrustKeySet);

                    AsymmetricKeyParameter pub = cwt.Cnf.Key.AsPublicKey();
                    SubjectPublicKeyInfo   spi = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
                    rpk.SetSubjectPublicKeyInfo(spi);

                    AuthenticationKey = cwt.Cnf.Key;
                    return;
                }
                catch {
                }

                TlsEvent ev = new TlsEvent(TlsEvent.EventCode.ServerCertificate)
                {
                    Certificate = rpk
                };

                EventHandler <TlsEvent> handler = TlsEventHandler;

                if (handler != null)
                {
                    handler(this, ev);
                }

                if (!ev.Processed)
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }

                AuthenticationKey = ev.KeyValue;
            }
Пример #5
0
        public static TradfriAuth GeneratePsk(string gatwayIp, string appName, string secret)
        {
            try
            {
                var authKey = new OneKey();
                authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(secret)));
                authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Client_identity")));
                var ep = new DTLSClientEndPoint(authKey);
                ep.Start();

                var request = new Request(Method.POST);
                request.SetUri($"coaps://{gatwayIp}" + $"/{(int)TradfriConstRoot.Gateway}/{(int)TradfriConstAttribute.Auth}/");
                request.EndPoint   = ep;
                request.AckTimeout = 5000;
                request.SetPayload($@"{{""{(int)TradfriConstAttribute.Identity}"":""{appName}""}}");

                request.Send();
                var resp = request.WaitForResponse(5000);
                if (resp == null)
                {
                    return(null);
                }

                return(JsonConvert.DeserializeObject <TradfriAuth>(resp.PayloadString));
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #6
0
        public TradfriAuth GenerateAppSecret(string GatewaySecret, string applicationName)
        {
            Response resp = new Response(StatusCode.Valid);

            OneKey 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")));
            DTLSClientEndPoint ep = new DTLSClientEndPoint(authKey);

            ep.Start();

            Request r = new Request(Method.POST);

            r.SetUri($"coaps://{_gatewayIp}" + $"/{(int)TradfriConstRoot.Gateway}/{(int)TradfriConstAttr.Auth}/");
            r.EndPoint   = ep;
            r.AckTimeout = 5000;
            r.SetPayload($@"{{""{(int)TradfriConstAttr.Identity}"":""{applicationName}""}}");

            r.Send();
            resp = r.WaitForResponse();

            if ((int)resp.StatusCode != 201)
            {
                RequestException <Response> .ConvertToException(MapToHttpStatusCode(resp.StatusCode), resp.StatusCode.ToString(), resp.UriQuery, "", resp.ResponseText, resp);
            }

            return(Convert <TradfriAuth>(resp.PayloadString));
        }
Пример #7
0
        public static void ClassSetup(TestContext ctx)
        {
            byte[]     cert   = Base64.Decode("MIIBHDCBz6ADAgECAhRzRMjlxi8nPr0B6DoN7e4sxwyb6jAFBgMrZXAwGDEWMBQGA1UEAwwNQ09TRSBDQSBUaHJlZTAeFw0xOTA3MDgwMTAyMjBaFw0yNzA5MjQwMTAyMjBaMBYxFDASBgNVBAMMC0NPU0UgRUUgU2l4MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEo0gYfGOYqcwGVra0OEiE0XXST/W4pTJ/HdTXZ7Ek/ycJZZn0jkHNQ9UCP7NJ16LOcZLUofev7OMHxct5DvuaPjAFBgMrZXADQQAqm5No83WC9W7tOkicP9wGu1HSdGCOR0CVjjzHfCfzRQkuSW2tRLBlstxzpqY6yrIuccMifhcrCdMe3fsPPS8G");
            CBORObject objKey = CBORObject.NewMap();

            objKey[CoseKeyKeys.KeyType]           = GeneralValues.KeyType_EC;
            objKey[CoseKeyKeys.Algorithm]         = AlgorithmValues.ECDSA_256;
            objKey[CoseKeyParameterKeys.EC_Curve] = GeneralValues.P256;
            objKey[CoseKeyParameterKeys.EC_D]     = CBORObject.FromObject(Hex.Decode("7D29C4C7CDCBB2209CAD01F3BB4C9009782F66C2E1A6C592DF838A0795A6D87B"));
            objKey[CoseKeyParameterKeys.EC_X]     = CBORObject.FromObject(Hex.Decode("A348187C6398A9CC0656B6B4384884D175D24FF5B8A5327F1DD4D767B124FF27"));
            objKey[CoseKeyParameterKeys.EC_Y]     = CBORObject.FromObject(Hex.Decode("096599F48E41CD43D5023FB349D7A2CE7192D4A1F7AFECE307C5CB790EFB9A3E"));

            OneKey key = new OneKey(objKey);

            X509Key = new TlsKeyPair(cert, key);

            cert   = Hex.Decode("3082011D3081D0A00302010202147344C8E5C62F273EBD01E83A0DEDEE2CC70C9BE9300506032B657030183116301406035504030C0D434F5345204341205468726565301E170D3139303730383031303231395A170D3237303932343031303231395A30173115301306035504030C0C434F534520454520466976653059301306072A8648CE3D020106082A8648CE3D03010703420004E8D9873804129C0A11238675C144CF00A7AF0E1A8ACF54A87BE76B9A0F2DBADF5384966EFD9C05B3DCEB3C074CF32410F033D962620C41F3892C0B94E3955D77300506032B65700341007BB0A5201998E6FC120364B96DD88211DD1FC907888C380E5A186BCD2F6A4CB238853EC22E5537CBCE5C157E59B4AEE71383372345932D0D40260857053FA608");
            objKey = CBORObject.NewMap();
            objKey[CoseKeyKeys.KeyType]           = GeneralValues.KeyType_EC;
            objKey[CoseKeyKeys.Algorithm]         = AlgorithmValues.ECDSA_256;
            objKey[CoseKeyParameterKeys.EC_Curve] = GeneralValues.P256;
            objKey[CoseKeyParameterKeys.EC_D]     = CBORObject.FromObject(Hex.Decode("019F4FD19429DE078B2A013F5218CD64C24FABA1F6F0BE924E628E63BC67A8AC"));
            objKey[CoseKeyParameterKeys.EC_X]     = CBORObject.FromObject(Hex.Decode("E8D9873804129C0A11238675C144CF00A7AF0E1A8ACF54A87BE76B9A0F2DBADF"));
            objKey[CoseKeyParameterKeys.EC_Y]     = CBORObject.FromObject(Hex.Decode("5384966EFD9C05B3DCEB3C074CF32410F033D962620C41F3892C0B94E3955D77"));

            X509Client = new TlsKeyPair(cert, new OneKey(objKey));
        }
Пример #8
0
            public void GetRpkKey(RawPublicKey rpk)
            {
                AsymmetricKeyParameter key;

                try {
                    key = PublicKeyFactory.CreateKey(rpk.SubjectPublicKeyInfo());
                }
                catch (Exception e) {
                    throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
                }

                if (key is ECPublicKeyParameters)
                {
                    ECPublicKeyParameters ecKey = (ECPublicKeyParameters)key;

                    string s      = ecKey.AlgorithmName;
                    OneKey newKey = new OneKey();
                    newKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_EC);
                    if (ecKey.Parameters.Curve.Equals(NistNamedCurves.GetByName("P-256").Curve))
                    {
                        newKey.Add(CoseKeyParameterKeys.EC_Curve, GeneralValues.P256);
                    }

                    newKey.Add(CoseKeyParameterKeys.EC_X, CBORObject.FromObject(ecKey.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned()));
                    newKey.Add(CoseKeyParameterKeys.EC_Y, CBORObject.FromObject(ecKey.Q.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned()));

                    if (_serverKeys != null)
                    {
                        foreach (OneKey k in _serverKeys)
                        {
                            if (k.Compare(newKey))
                            {
                                AuthenticationKey = k;
                                return;
                            }
                        }
                    }

                    TlsEvent ev = new TlsEvent(TlsEvent.EventCode.ServerCertificate)
                    {
                        KeyValue = newKey
                    };

                    EventHandler <TlsEvent> handler = TlsEventHandler;
                    if (handler != null)
                    {
                        handler(this, ev);
                    }

                    if (!ev.Processed)
                    {
                        //                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                    }
                }
                else
                {
                    // throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }
            }
Пример #9
0
        public void setUp()
        {
            CBORObject cnKey = CBORObject.NewMap();

            cnKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            cnKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(rgbKey256));
            cnKey256 = new OneKey(cnKey);
        }
Пример #10
0
        public void OneTimeSetup()
        {
            RpkOneKey = OneKey.GenerateKey(AlgorithmValues.ECDSA_256, GeneralValues.KeyType_EC, "P-256");

            PskOneKey = new OneKey();
            PskOneKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskOneKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[10]));
        }
Пример #11
0
 /// <summary>
 /// Instantiates a new TCP endpoint with the specific channel and configuration
 /// </summary>
 /// <param name="tlsKey">Authentication information</param>
 /// <param name="channel">Channel interface to the transport</param>
 /// <param name="config">Configuration information for the transport</param>
 private TLSClientEndPoint(OneKey tlsKey, TLSClientChannel channel, ICoapConfig config) : base(channel, config)
 {
     Stack.Remove("Reliability");
     MessageEncoder = TcpCoapMesageEncoder;
     MessageDecoder = TcpCoapMessageDecoder;
     EndpointSchema = "coaps";
     _userKey       = tlsKey;
 }
Пример #12
0
        public void AddRecipient(byte[] recipientId, OneKey signKey)
        {
            EntityContext x = DeriveEntityContext(_masterSecret, recipientId, _salt, Sender.Algorithm, null);

            x.SigningKey = signKey;

            Recipients.Add(recipientId, x);
        }
Пример #13
0
 /// <summary>
 /// Create a PSK version of a TLS Key Pair
 /// </summary>
 /// <param name="sharedSecret">PSK value</param>
 public TlsKeyPair(OneKey sharedSecret)
 {
     this.PrivateKey = sharedSecret ?? throw new ArgumentNullException(nameof(sharedSecret));
     if (!sharedSecret.HasKeyType((int)GeneralValuesInt.KeyType_Octet))
     {
         throw new ArgumentException("Not a shared secret key");
     }
     CertType = 0;
 }
Пример #14
0
        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);
        }
Пример #15
0
        private static OneKey GetKey(string applicationId, string apiKey)
        {
            var authKey = new OneKey();

            authKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            authKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes(apiKey)));
            authKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes(applicationId)));
            return(authKey);
        }
Пример #16
0
        public void testSetKey()
        {
            OneKey cnKey    = null;
            Signer instance = new Signer();

            instance.setKey(cnKey);
            // TODO review the generated test code and remove the default call to fail.
            fail("The test case is a prototype.");
        }
Пример #17
0
        /// <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);
        }
Пример #18
0
        protected TlsSignerCredentials GetECDsaSignerCredentials()
        {
#if SUPPORT_RPK
            if (_tlsKeyPair != null && _tlsKeyPair.CertType == CertificateType.RawPublicKey)
            {
                OneKey k = _tlsKeyPair.PublicKey;
                if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                    k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                {
                    X9ECParameters         p          = k.GetCurve();
                    ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
                    ECPrivateKeyParameters privKey    = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(k[CoseKeyParameterKeys.EC_D]), parameters);

                    ECPoint point = k.GetPoint();
                    ECPublicKeyParameters param = new ECPublicKeyParameters(point, parameters);

                    SubjectPublicKeyInfo spi = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(param);

                    return(new DefaultTlsSignerCredentials(mContext, new RawPublicKey(spi), privKey, new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                }
            }
#endif

#if SUPPORT_TLS_CWT
            if (_tlsKeyPair != null && _tlsKeyPair.CertType == CertificateType.CwtPublicKey)
            {
                OneKey k = _tlsKeyPair.PublicCwt.Cnf.Key;
                if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                    k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                {
                    X9ECParameters         p          = k.GetCurve();
                    ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
                    ECPrivateKeyParameters privKey    = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(k[CoseKeyParameterKeys.EC_D]), parameters);

                    return(new DefaultTlsSignerCredentials(mContext, new CwtPublicKey(_tlsKeyPair.PublicCwt.EncodeToBytes()), privKey, new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                }
            }
#endif

            TlsEvent e = new TlsEvent(TlsEvent.EventCode.SignCredentials)
            {
                CipherSuite = KeyExchangeAlgorithm.ECDH_ECDSA
            };

            EventHandler <TlsEvent> handler = TlsEventHandler;
            if (handler != null)
            {
                handler(this, e);
            }

            if (e.SignerCredentials != null)
            {
                return(e.SignerCredentials);
            }
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }
Пример #19
0
            public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest)
            {
                if (certificateRequest.CertificateTypes == null ||
                    !Arrays.Contains(certificateRequest.CertificateTypes, ClientCertificateType.ecdsa_sign))
                {
                    return(null);
                }

#if SUPPORT_RPK
                if (_rawPublicKey != null)
                {
                    OneKey k = _rawPublicKey;
                    if (k.HasKeyType((int)COSE.GeneralValuesInt.KeyType_EC2) &&
                        k.HasAlgorithm(COSE.AlgorithmValues.ECDSA_256))
                    {
                        X9ECParameters         p          = k.GetCurve();
                        ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
                        ECPrivateKeyParameters privKey    = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(k[CoseKeyParameterKeys.EC_D]), parameters);

                        ECPoint point = k.GetPoint();
                        ECPublicKeyParameters param = new ECPublicKeyParameters("ECDSA", point, /*parameters*/ SecObjectIdentifiers.SecP256r1);

                        SubjectPublicKeyInfo spi = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(param);

                        return(new DefaultTlsSignerCredentials(_mContext, new RawPublicKey(spi), privKey, new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                    }
                }

                /*
                 * byte[] certificateTypes = certificateRequest.CertificateTypes;
                 * if (certificateTypes == null || !Arrays.Contains(certificateTypes, ClientCertificateType.rsa_sign))
                 *  return null;
                 *
                 * return TlsTestUtilities.LoadSignerCredentials(mContext, certificateRequest.SupportedSignatureAlgorithms,
                 *  SignatureAlgorithm.rsa, "x509-client.pem", "x509-client-key.pem");
                 */
#endif
                // If we did not fine appropriate signer credientials - ask for help

                TlsEvent e = new TlsEvent(TlsEvent.EventCode.SignCredentials)
                {
                    CipherSuite = KeyExchangeAlgorithm.ECDHE_ECDSA
                };

                EventHandler <TlsEvent> handler = TlsEventHandler;
                if (handler != null)
                {
                    handler(this, e);
                }

                if (e.SignerCredentials != null)
                {
                    return(e.SignerCredentials);
                }
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }
Пример #20
0
        public void nullKey()
        {
            Sign1Message msg = new Sign1Message();
            OneKey       key = null;

            msg.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.ECDSA_256, Attributes.PROTECTED);
            msg.SetContent(rgbContent);
            Assert.ThrowsException <NullReferenceException>(() =>
                                                            msg.Sign(key));
        }
Пример #21
0
        public static void OneTimeSetup(TestContext ctx)
        {
#if SUPPORT_RPK
            RpkOneKey = OneKey.GenerateKey(AlgorithmValues.ECDSA_256, GeneralValues.KeyType_EC, "P-256");
#endif

            PskOneKey = new OneKey();
            PskOneKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            PskOneKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(new byte[10]));
        }
Пример #22
0
        public void Setup()
        {
            keyOctet = new OneKey();
            keyOctet.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            keyOctet.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(octetKeyValue));
            keyOctet.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(octetKeyID));

            keyEdDSA = OneKey.GenerateKey(null, GeneralValues.KeyType_EC, "P-256");
            keyDSA   = OneKey.GenerateKey(null, GeneralValues.KeyType_OKP, "Ed25519");
        }
Пример #23
0
        public void setUp()
        {
            recipient256 = new Recipient();
            recipient256.AddAttribute(HeaderKeys.Algorithm, AlgorithmValues.Direct, Attributes.UNPROTECTED);
            CBORObject key256 = CBORObject.NewMap();

            key256.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            key256.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(rgbKey256));
            cnKey256 = new OneKey(key256);
            recipient256.SetKey(cnKey256);
        }
Пример #24
0
        public void Create_Test2()
        {
            OneKey key = new OneKey();

            key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_RSA);

            Exception e = Assert.Throws <Exception>(() => new EdhocInitiator(key));

            Assert.That(e.Message, Is.EqualTo("Unknown key type for secret"));
            ;
        }
Пример #25
0
 /// <summary>
 /// Create a TLS Key pair object for doing X.509 certificate authentication
 /// </summary>
 /// <param name="certificate"></param>
 /// <param name="privateKey"></param>
 public TlsKeyPair(byte[] certificate, OneKey privateKey)
 {
     this.PrivateKey = privateKey ?? throw new ArgumentNullException(nameof(privateKey));
     if (certificate == null)
     {
         throw new ArgumentNullException(nameof(certificate));
     }
     this.X509Certificate = new X509CertificateStructure[1];
     X509Certificate[0]   = new X509CertificateParser().ReadCertificate(certificate).CertificateStructure;
     CertType             = CertificateType.X509; // X.509 Certificate
 }
Пример #26
0
        public void AddRecipient(byte[] recipientId, OneKey signKey)
        {
            if (!signKey.HasAlgorithm(Sender.SigningAlgorithm))
            {
                throw new ArgumentException("signature algorithm not correct");
            }
            EntityContext x = DeriveEntityContext(_masterSecret, GroupId, recipientId, _salt, Sender.Algorithm);

            x.SigningKey = signKey;

            Recipients.Add(recipientId, x);
        }
Пример #27
0
        static void GenerateKeys(string fileName)
        {
            if (fileName == null)
            {
                fileName = "ServerKeys.cbor";
            }

            KeySet keys = new KeySet();
            OneKey key;

            for (int i = 0; i < 4; i++)
            {
                key = new OneKey();
                key.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
                if (i == 3)
                {
                    key.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("Key#2")));
                }
                else
                {
                    key.Add(CoseKeyKeys.KeyIdentifier,
                            CBORObject.FromObject(Encoding.UTF8.GetBytes("Key#" + i.ToString())));
                }
                if (i == 3)
                {
                    key.Add(CoseKeyKeys.Algorithm, AlgorithmValues.AES_CCM_64_128_128);
                }
                else
                {
                    key.Add(CoseKeyKeys.Algorithm, AlgorithmValues.AES_CCM_64_64_128);
                }
                key.Add(CBORObject.FromObject("KDF"), AlgorithmValues.dir_kdf);
                key.Add(CBORObject.FromObject("SenderID"), CBORObject.FromObject(Encoding.UTF8.GetBytes("client")));
                key.Add(CBORObject.FromObject("RecipID"), CBORObject.FromObject(Encoding.UTF8.GetBytes("server")));
                byte[] keyValue = new byte[35];
                for (int j = 0; j < keyValue.Length; j++)
                {
                    keyValue[j] = (byte)(((i + 1) * (j + 1)));
                }
                key.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(keyValue));

                keys.AddKey(key);
            }

            FileStream fs = new FileStream(fileName, FileMode.Create);

            using (BinaryWriter writer = new BinaryWriter(fs)) {
                writer.Write(keys.EncodeToBytes());
                writer.Close();
            }

            Environment.Exit(0);
        }
Пример #28
0
        private static void GenOscore(string[] cmds)
        {
            int    count     = int.Parse(cmds[1]);
            int    keyType   = int.Parse(cmds[2]);
            string algParams = cmds[3];

            for (int i = 0; i < count; i++)
            {
                OneKey key = OneKey.GenerateKey(null, CBORObject.FromObject(keyType), algParams);
                Console.WriteLine("*** " + key.EncodeToCBORObject().ToString());
            }
        }
Пример #29
0
        private static void AddTlsKey(string[] commands)
        {
            if (commands.Length != 3)
            {
                Console.WriteLine("Incorrect number of arguments: " + commands.Length);
                return;
            }

            CBORObject cbor = CBORDiagnostics.Parse(commands[2]);
            OneKey     key  = new OneKey(cbor);

            _TlsKeys.Add(commands[1], key);
        }
Пример #30
0
            public virtual byte[] GetPsk(byte[] identity)
            {
                foreach (OneKey key in _userKeys)
                {
                    if (!key.HasKeyType((int)COSE.GeneralValuesInt.KeyType_Octet))
                    {
                        continue;
                    }

                    if (identity == null)
                    {
                        if (key.HasKid(null))
                        {
                            AuthenticationKey = key;
                            return((byte[])key[CoseKeyParameterKeys.Octet_k].GetByteString().Clone());
                        }
                    }
                    else
                    {
                        if (key.HasKid(identity))
                        {
                            AuthenticationKey = key;
                            return((byte[])key[CoseKeyParameterKeys.Octet_k].GetByteString().Clone());
                        }
                    }
                }


                TlsEvent e = new TlsEvent(TlsEvent.EventCode.UnknownPskName)
                {
                    PskName = identity
                };
                EventHandler <TlsEvent> handler = TlsEventHandler;

                if (handler != null)
                {
                    handler(this, e);
                }

                if (e.KeyValue != null)
                {
                    if (e.KeyValue.HasKeyType((int)COSE.GeneralValuesInt.KeyType_Octet))
                    {
                        AuthenticationKey = e.KeyValue;
                        return((byte[])e.KeyValue[CoseKeyParameterKeys.Octet_k].GetByteString().Clone());
                    }
                }

                return(null);
            }