예제 #1
0
        public static KeyContainer GetKeys(string name)
        {
            XDocument keyDocument = XDocument.Load(name);

            KeyContainer container = new KeyContainer();

            container.DiFmPremiumKey = (from c in keyDocument.Root.Elements() where c.Attribute("type").Value == "difm"
                                        select c).FirstOrDefault().Attribute("value").Value;
            container.LastFmKey = (from c in keyDocument.Root.Elements()
                                   where c.Attribute("type").Value == "lastfm"
                                   select c).FirstOrDefault().Attribute("value").Value;
            container.MsaKey = (from c in keyDocument.Root.Elements()
                                where c.Attribute("type").Value == "msa"
                                select c).FirstOrDefault().Attribute("value").Value;
            container.ZumoKey = (from c in keyDocument.Root.Elements()
                                 where c.Attribute("type").Value == "zumo"
                                 select c).FirstOrDefault().Attribute("value").Value;
            container.ZumoUrl = (from c in keyDocument.Root.Elements()
                                 where c.Attribute("type").Value == "zumourl"
                                 select c).FirstOrDefault().Attribute("value").Value;
            container.LastFmSecret = (from c in keyDocument.Root.Elements()
                                      where c.Attribute("type").Value == "lastfmsecret"
                                      select c).FirstOrDefault().Attribute("value").Value;

            return(container);
        }
예제 #2
0
        public void HashTestFromWiki()
        {
            //GOST("") = 981E5F3CA30C841487830F84FB433E13AC1101569B9C13584AC483234CD656C0
            byte[] data = Encoding.UTF8.GetBytes("");
            byte[] hash = KeyContainer.ComputeHash(data);

            var hexString = HexEncoding.ToString(hash);

            Assert.AreEqual("981E5F3CA30C841487830F84FB433E13AC1101569B9C13584AC483234CD656C0", hexString);


            //GOST("a") = E74C52DD282183BF37AF0079C9F78055715A103F17E3133CEFF1AACF2F403011
            data = Encoding.UTF8.GetBytes("a");
            hash = KeyContainer.ComputeHash(data);

            hexString = HexEncoding.ToString(hash);
            Assert.AreEqual("E74C52DD282183BF37AF0079C9F78055715A103F17E3133CEFF1AACF2F403011", hexString);


            //GOST("abc") = B285056DBF18D7392D7677369524DD14747459ED8143997E163B2986F92FD42C
            data = Encoding.UTF8.GetBytes("abc");
            hash = KeyContainer.ComputeHash(data);

            hexString = HexEncoding.ToString(hash);
            Assert.AreEqual("B285056DBF18D7392D7677369524DD14747459ED8143997E163B2986F92FD42C", hexString);


            //GOST("message digest") = BC6041DD2AA401EBFA6E9886734174FEBDB4729AA972D60F549AC39B29721BA0
            data = Encoding.UTF8.GetBytes("message digest");
            hash = KeyContainer.ComputeHash(data);

            hexString = HexEncoding.ToString(hash);
            Assert.AreEqual("BC6041DD2AA401EBFA6E9886734174FEBDB4729AA972D60F549AC39B29721BA0", hexString);
        }
        // Post api/courses
        public IEnumerable <CourseInfo> Post([FromUri] int coursesType, [FromBody] KeyContainer keyContainer)
        {
            if (!Enum.IsDefined(typeof(CoursesTakenType), coursesType))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Course Taken Type must be 0, 1 or 2"));
            }

            string key = keyContainer.GetNormalizedKey();

            SusiParser.Parser parser;
            if (GlobalHost.Instance.TryGetValue(key, out parser))
            {
                try
                {
                    IEnumerable <CourseInfo> info = parser.GetCourses((CoursesTakenType)coursesType);
                    GlobalHost.Instance.Logger.LogCoursesRequest(this.GetClientIp(), (CoursesTakenType)coursesType);
                    return(info);
                }
                catch (WebException)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadGateway, "Can't load data from susi"));
                }
            }

            // If the key was not found
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No such key / key expired "));
        }
예제 #4
0
        public void SetUp()
        {
            ActualEvent   = new List <TestEvent>();
            ExpectedEvent = new List <TestEvent>();

            Remotes = new List <IPEndPoint>();
            Routers = new List <IAudioRouter>();

            NetworkMoq = new Mock <ITcpСontroller>();
            NetworkMoq
            .Setup(s => s.Send(It.IsAny <IPEndPoint>(), It.IsAny <ArraySegment <byte> >()))
            .Callback <IPEndPoint, ArraySegment <byte> >((remote, data) =>
            {
                ActualEvent.Add(new TestEvent(remote, data.ToArray()));
            });
            NetworkMoq
            .Setup(s => s.Disconnect(It.IsAny <IPEndPoint>()))
            .Callback <IPEndPoint>((remote) =>
            {
                ActualEvent.Add(new TestEvent(remote));
                NetworkMoq.Raise(s => s.ConnectionClosing += null, remote);
            });

            MessageFactory = new MessageFactory(true);
            Container      = new KeyContainer();
            Core           = new CoreApi(NetworkMoq.Object, MessageFactory);
            Calls          = new CallController(Container, () =>
            {
                Routers.Add(new BridgeRouter(new AudioProvider(NetworkMoq.Object)));
                return(Routers[^ 1]);
            });
예제 #5
0
        bool RemoveContainer(Config cfg)
        {
            string containerName = cfg.ContainerName;

            Console.WriteLine("Removing container '{0}'...", containerName);
            if (String.IsNullOrEmpty(containerName))
            {
                Failure(cfg, "Unspecified container name.");
                return(true);
            }

            try
            {
                KeyContainer.RemoveFromDisk(containerName, cfg.UseMachinePath);

                Console.WriteLine("Success.");
            }
            catch (Exception ex)
            {
                Failure(ex, cfg);
                return(true);
            }

            return(false);
        }
예제 #6
0
 /// <summary>
 ///     Проверка подписи.
 /// </summary>
 /// <param name="request">Данные.</param>
 /// <returns>True - провека прошла успешно, иначе False.</returns>
 public bool VerifySignature(VerifySignatureRequest request)
 {
     log.Debug("VerifySignature: {0}", request);
     byte[] signatureValue = Convert.FromBase64String(request.Signature);
     byte[] dataValue      = Encoding.UTF8.GetBytes(request.Data);
     byte[] publicKeyValue = Convert.FromBase64String(request.PublicKey);
     return(KeyContainer.VerifySignature(signatureValue, dataValue, publicKeyValue));
 }
예제 #7
0
 public void ExportPublicKey()
 {
     using (KeyContainer keyContainer = KeyContainer.Open(Container, ContainerPassword))
     {
         byte[] key = keyContainer.ExportPublicKey();
         CollectionAssert.IsNotEmpty(key);
     }
 }
예제 #8
0
 public ClientContext(string ApplicationName, string passcode, Form form)
 {
     _ContextManager  = Utils.COMCreateObject <IContextManager>("CCOW.ContextManager");
     _KeyContainer    = new KeyContainer(ApplicationName);
     _ApplicationName = ApplicationName;
     _Passcode        = passcode;
     _Form            = form;
 }
예제 #9
0
        /// <summary>
        /// Captures the current values for a given entity and creates a keyframe
        /// at the given time and with the captured values
        /// </summary>
        /// <param name="entity">entity to capture</param>
        /// <param name="time">Time to create keyframe at</param>
        public void Capture(Entity entity, int time)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity), "entity cannot be null");
            }
            PerfStopwatch stopwatch = PerfStopwatch.StartNew("Capturing New keyframe");
            //Get all behaviours on entity
            IEnumerable <BehaviourComponent> behaviours   = entity.Components;
            List <KeyframePropertyData>      propertyData = new List <KeyframePropertyData>();

            foreach (BehaviourComponent behaviour in behaviours)
            {
                //Check if the cache contains entry for this behaviour
                if (!keyframeInfoCache.ContainsKey(behaviour))
                {
                    //Get all properties with the KeyframeAnimationProperty attribute
                    Type behaviourType = behaviour.GetType();
                    IEnumerable <PropertyInfo> reflectedProperties = behaviourType.GetProperties().Where(
                        prop => Attribute.IsDefined(prop, typeof(KeyframeProperty))
                        );
                    List <KeyframePropertyInfo> propInfos = new List <KeyframePropertyInfo>();
                    foreach (PropertyInfo propInfo in reflectedProperties)
                    {
                        if (!propInfo.CanWrite || !propInfo.CanRead)
                        {
                            DebugUtil.LogWithLocation($"Property {propInfo.Name} needs both read and write access");
                            continue;
                        }
                        propInfos.Add(new KeyframePropertyInfo(propInfo, PropertyType.Interpolatable));
                    }

                    keyframeInfoCache.Add(behaviour, propInfos.ToArray());
                }

                KeyframePropertyInfo[] properties = keyframeInfoCache[behaviour];
                for (int i = 0, l = properties.Length; i < l; i++)
                {
                    object currentPropertyValue = properties[i].Property.GetValue(behaviour);
                    KeyframePropertyData key    = new ValueKeyframe(properties[i], behaviour, currentPropertyValue);
                    //Add it to the timeline
                    propertyData.Add(key);
                }
            }
            //Check if entity has a timeline or if we need to create one for it
            if (!timelines.ContainsKey(entity))
            {
                CreateTimeline(entity);
            }

            KeyContainer newKey = new KeyContainer(propertyData);

            newKey.Time = time;
            timelines[entity].AddKeyframe(newKey);

            stopwatch.Stop();
        }
예제 #10
0
        /// <summary>
        ///     Проверка подписи.
        /// </summary>
        /// <param name="request">Данные.</param>
        /// <returns>True - провека прошла успешно, иначе False.</returns>
        public bool VerifyCertificate(VerifySignatureCertRequest request)
        {
            log.Debug("VerifySignatureSert: {0}", request);
            byte[] signatureValue   = Convert.FromBase64String(request.Signature);
            byte[] dataValue        = Encoding.UTF8.GetBytes(request.Data);
            byte[] certificateValue = Convert.FromBase64String(request.Certificate);

            return(KeyContainer.VerifyCertificate(signatureValue, dataValue, certificateValue));
        }
예제 #11
0
 /// <summary>
 ///     Подсчет хэша.
 /// </summary>
 /// <param name="data">Данные.</param>
 /// <returns>Хэш.</returns>
 public string ComputeHash(string data)
 {
     log.Debug("ComputeHash: data: {0}", data);
     if (data == null)
     {
         throw new WebFaultException(HttpStatusCode.BadRequest);
     }
     byte[] dataValue = Encoding.UTF8.GetBytes(data);
     return(Convert.ToBase64String(KeyContainer.ComputeHash(dataValue)));
 }
예제 #12
0
        public void ComputeHash()
        {
            byte[] data = GetRandomData();

            byte[] hash = KeyContainer.ComputeHash(data);

            const int HashLength = 32;

            Assert.AreEqual(HashLength, hash.Length);
        }
예제 #13
0
 public bool IsHotkeyRegistered(KeyContainer Container)
 {
     foreach (KeyContainer CurKey in RegisteredHokeys)
     {
         if (CurKey.Equals(Container))
         {
             return(true);
         }
     }
     return(false);
 }
예제 #14
0
        public void GetCertificatePublicKey()
        {
            using (KeyContainer keyContainer = KeyContainer.Open(ContainerSert, ContainerPassword))
            {
                var certificateRawData = keyContainer.ExportCertificateData();
                var publicKeyFromCert  = KeyContainer.GetCertificatePublicKey(certificateRawData);

                var containerKey = keyContainer.ExportPublicKey();

                Assert.AreEqual(containerKey, publicKeyFromCert);
            }
        }
예제 #15
0
        public void TestCanStoreAndRetrieveKeyFromKeyContainer()
        {
            var container = new KeyContainer();

            container.SetKey(new SigningKey
            {
                KeyId = "first"
            });
            var key = container.GetKey();

            Assert.AreEqual("first", key.KeyId);
        }
예제 #16
0
 public SerializedKey Protect(KeyContainer key)
 {
     ProtectWasCalled = true;
     return(new SerializedKey
     {
         Id = key.Id,
         Algorithm = key.Algorithm,
         IsX509Certificate = key.HasX509Certificate,
         Created = DateTime.UtcNow,
         Data = KeySerializer.Serialize(key),
     });
 }
예제 #17
0
        // I know, I know post should not be used for getting stuff but f**k it
        // POST api/roles
        public IEnumerable <StudentRole> Post([FromBody] KeyContainer key)
        {
            Parser parser;

            if (GlobalHost.Instance.TryGetValue(key.GetNormalizedKey(), out parser))
            {
                return(parser.Roles);
            }

            // If the key was not found
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No such key / key expired "));
        }
예제 #18
0
        // Delete api/login
        public HttpResponseMessage Delete([FromBody] KeyContainer keyContainer)
        {
            string key = keyContainer.Key.Replace("\"", string.Empty);

            if (GlobalHost.Instance.TryRemove(key))
            {
                GlobalHost.Instance.Logger.LogLogoutRequest(key, this.GetClientIp());

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            return(Request.CreateResponse(HttpStatusCode.NotFound));
        }
예제 #19
0
        // PUT api/roles
        public void Put([FromUri] int roleIndex, [FromBody] KeyContainer key)
        {
            Parser parser;

            if (GlobalHost.Instance.TryGetValue(key.GetNormalizedKey(), out parser))
            {
                parser.ChangeRole(parser.Roles[roleIndex]);
                return;
            }

            // If the key was not found
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No such key / key expired "));
        }
예제 #20
0
        /// <summary>
        ///     Подпись хэша.
        /// </summary>
        /// <param name="hash">Хэш.</param>
        /// <returns>Подпись хэша.</returns>
        public string SignHash(string hash)
        {
            if (string.IsNullOrWhiteSpace(hash))
            {
                throw new WebFaultException(HttpStatusCode.BadRequest);
            }

            log.Debug("SignHash: hash: {0}, keyNumber: {1}", hash, KeyNumber.Signature);
            byte[] hashValue = Convert.FromBase64String(hash);
            using (KeyContainer keyContainer = KeyContainer.Open(Container, ContainerPassword))
            {
                byte[] signature = keyContainer.SignHash(hashValue, KeyNumber.Signature);
                return(Convert.ToBase64String(signature));
            }
        }
예제 #21
0
        public void TestStoringKeyReplacesOldOne()
        {
            var container = new KeyContainer();

            container.SetKey(new SigningKey
            {
                KeyId = "first"
            });
            container.SetKey(new SigningKey
            {
                KeyId = "second"
            });
            var key = container.GetKey();

            Assert.AreEqual("second", key.KeyId);
        }
예제 #22
0
        public void SignHash()
        {
            byte[] data = GetRandomData();

            byte[] signature;
            byte[] hash = KeyContainer.ComputeHash(data);

            using (KeyContainer keyContainer = KeyContainer.Open(Container, ContainerPassword))
            {
                signature = keyContainer.SignHash(hash, KeyNumber.Signature);
            }

            byte[] publicKey = KeyContainer.ExportPublicKey(Container);
            bool   result    = KeyContainer.VerifySignature(signature, data, publicKey);

            Assert.IsTrue(result);
        }
예제 #23
0
        public void TestMethod1()
        {
            AesFileEncryptionPrivider.Create("hamed");
            var key1 = new KeyContainer();
            var key2 = new KeyContainer();

            key1.ExportPrivateKey("key.dat");
            var t1 = new Transaction(1, key1.PublicKeyS, key2.PublicKeyS, 15.5, 0, Guid.NewGuid().ToString().GetHashString());

            t1.GenerateSignture("key.dat");
            Assert.IsTrue(t1.IsSignatureVerified);
            key2.ExportPrivateKey("key.dat");
            t1.GenerateSignture("key.dat");
            Assert.IsFalse(t1.IsSignatureVerified);
            key1.Dispose();
            key2.Dispose();
        }
예제 #24
0
        public void SignCertigicateSignature()
        {
            byte[] data = GetRandomData();

            byte[] signature, certificateRawData;
            byte[] hash = KeyContainer.ComputeHash(data);


            using (KeyContainer keyContainer = KeyContainer.Open(ContainerSert, ContainerPassword))
            {
                signature          = keyContainer.SignHash(hash, KeyNumber.Signature);
                certificateRawData = keyContainer.ExportCertificateData();
            }

            bool result = KeyContainer.VerifyCertificate(signature, data, certificateRawData);

            Assert.IsTrue(result);
        }
예제 #25
0
        public void TransactionTest1()
        {
            Init.Initizer("Xunit", () => "Xunit");
            var key1 = new KeyContainer();
            var key2 = new KeyContainer();

            key1.ExportPrivateKey("key.dat");
            DataUtilities.Principles.TryAdd((DataUtilities.Version).GetPrinciplesKey(Principles.PrinciplesType.Transaction), new Galleon.Principles.TransactionPrinciples(1, "hi", "short", 1000, 1));
            var t1 = new Galleon.ContractManager.TransactionManager.Transaction(DataUtilities.Version, key1.PublicKeyS, key2.PublicKeyS, 15.5, 0, Guid.NewGuid().ToString().GetHashString(HashAlgorithms.SHA256));

            t1.GenerateSignture("key.dat");
            Assert.True(t1.IsSignatureVerified);
            key2.ExportPrivateKey("key.dat");
            t1.GenerateSignture("key.dat");
            Assert.False(t1.IsSignatureVerified);
            key1.Dispose();
            key2.Dispose();
        }
예제 #26
0
        public bool RegisterHotkey(KeyContainer Container)
        {
            //Check if hotkey is already registered, else add
            if (IsHotkeyRegistered(Container))
            {
                return(false);
            }
            Container.HotkeyId = ++keyCounter;
            //New key, register it.
            var retVal = RegisterHotKey(_windowHandle, Container.HotkeyId, Container.GetKeyModifiers(), Container.Key);

            Console.WriteLine($"RegisterHotKey for id {Container.HotkeyId} returned {retVal}");
            if (retVal == 0)
            {
                return(false);
            }
            RegisteredHokeys.Add(Container);
            return(true);
        }
예제 #27
0
        public void IsKeyRotationRequired_when_no_active_key_should_be_true()
        {
            {
                var keys = new KeyContainer[] {
                    CreateKey(_options.KeyRetirementAge.Add(TimeSpan.FromDays(1))),
                };
                var result = _subject.IsKeyRotationRequired(keys);
                result.Should().BeTrue();
            }

            {
                var keys = new[] {
                    CreateKey(_options.RotationInterval.Add(TimeSpan.FromDays(1))),
                };

                var result = _subject.IsKeyRotationRequired(keys);
                result.Should().BeTrue();
            }
        }
    /// <inheritdoc/>
    public SerializedKey Protect(KeyContainer key)
    {
        var data = KeySerializer.Serialize(key);

        if (_options.DataProtectKeys)
        {
            data = _dataProtectionProvider.Protect(data);
        }

        return(new SerializedKey
        {
            Version = 1,
            Created = DateTime.UtcNow,
            Id = key.Id,
            Algorithm = key.Algorithm,
            IsX509Certificate = key.HasX509Certificate,
            Data = data,
            DataProtected = _options.DataProtectKeys,
        });
    }
예제 #29
0
        // POST api/student
        public StudentInfo Post([FromBody] KeyContainer keyContainer)
        {
            string key = keyContainer.GetNormalizedKey();

            SusiParser.Parser parser;
            if (GlobalHost.Instance.TryGetValue(key, out parser))
            {
                try
                {
                    StudentInfo info = parser.GetStudentInfo();
                    GlobalHost.Instance.Logger.LogStudentRequest(this.GetClientIp());
                    return(info);
                }
                catch (WebException)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadGateway, "Can't load data from susi"));
                }
            }

            // If the key was not found
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No such key / key expired "));
        }
예제 #30
0
    internal async Task <KeyContainer> CreateAndStoreNewKeyAsync(SigningAlgorithmOptions alg)
    {
        _logger.LogTrace("Creating new key.");

        var now = _clock.UtcNow.UtcDateTime;
        var iss = await _issuerNameService.GetCurrentAsync();

        KeyContainer container = null;

        if (alg.IsRsaKey)
        {
            var rsa = CryptoHelper.CreateRsaSecurityKey(_options.KeyManagement.RsaKeySize);

            container = alg.UseX509Certificate ?
                        new X509KeyContainer(rsa, alg.Name, now, _options.KeyManagement.KeyRetirementAge, iss) :
                        (KeyContainer) new RsaKeyContainer(rsa, alg.Name, now);
        }
        else if (alg.IsEcKey)
        {
            var ec = CryptoHelper.CreateECDsaSecurityKey(CryptoHelper.GetCurveNameFromSigningAlgorithm(alg.Name));
            // X509 certs don't currently work with EC keys.
            container = //_options.KeyManagement.WrapKeysInX509Certificate ? //new X509KeyContainer(ec, alg, now, _options.KeyManagement.KeyRetirementAge, iss) :
                        (KeyContainer) new EcKeyContainer(ec, alg.Name, now);
        }
        else
        {
            throw new Exception($"Invalid alg '{alg}'");
        }

        var key = _protector.Protect(container);
        await _store.StoreKeyAsync(key);

        _logger.LogDebug("Created and stored new key with kid {kid}.", container.Id);

        return(container);
    }