Ejemplo n.º 1
0
        protected virtual string _AddSalt(string token, TokenSalt salt)
        {
            token = _Replace(token, 2, salt.VersionPosition.ToString());

            // add version
            token = _SetVersion(token, salt.VersionPosition);

            // add salt
            token = _Replace(token, salt.VersionPosition + 1, salt.SaltPosition.ToString("D2"));
            token = _Replace(token, salt.SaltPosition, salt.Salt);

            // add data and timestamp
            token = _Replace(token, salt.VersionPosition + 5, salt.DataLength.ToString("D2"));
            token = _Replace(token, salt.VersionPosition + 3, salt.DataPosition.ToString("D2"));

            if (!string.IsNullOrEmpty(salt.Data))
            {
                if (salt.Data.Length > _settings.DataMaxlength - _TIMESTAMP_LENGTH)
                {
                    var message = $"data length is not in range, max length is {_settings.DataMaxlength - _TIMESTAMP_LENGTH}";

                    throw new ArgumentOutOfRangeException(nameof(salt.Data), message);
                }

                token = _Replace(token, salt.DataPosition, salt.Data);
            }

            token = _Replace(token, salt.DataPosition + _settings.DataMaxlength - _TIMESTAMP_LENGTH, salt.Timestamp.ToString("x8"));

            // apply backpack
            return(_backpack.Encode(token));
        }
Ejemplo n.º 2
0
        public string Encrypt(string input, string key, string data = null)
        {
            var versionPosition = _Random.Next(_settings.VersionPosStart, _settings.VersionPosEnd - _settings.VersionLength);
            var saltPosition    = _Random.Next(_settings.SaltPosStart, _settings.SaltPosEnd - _settings.SaltLength);
            var dataPosition    = _Random.Next(_settings.DataPosStart, _settings.DataPosEnd - _settings.DataMaxlength);
            var timestamp       = DateTime.Now.ToTimestamp();
            var salt            = new TokenSalt(_GenerateSalt(), data, timestamp, versionPosition, saltPosition, dataPosition, data?.Length ?? 0);

            return(Encrypt(input, key, salt));
        }
Ejemplo n.º 3
0
        public string Encrypt(string input, string key, TokenSalt salt)
        {
            var keyBuffer = Encoding.UTF8.GetBytes(key + salt.Salt);

            using (var sha = IncrementalHash.CreateHMAC(_settings.HashAlgorithm, keyBuffer))
            {
                sha.AppendData(Encoding.UTF8.GetBytes(input));

                var buffer = sha.GetHashAndReset();
                var token  = BitConverter.ToString(buffer).Replace("-", string.Empty).ToLower();

                return(_AddSalt(token, salt));
            }
        }