Пример #1
0
        /// <summary>
        /// Gets a value from the setting cache
        /// </summary>
        /// <typeparam name="T">Desired type</typeparam>
        /// <param name="key">Setting key</param>
        /// <param name="defaultValue">Default value in case of failed lookup / conversion</param>
        /// <returns>Found value or default value</returns>
        public T Get <T>(string key, T defaultValue = default(T))
        {
            try
            {
                object value;
                if (_data.TryGetValue(_cryptoProvider.Hash(key), out value))
                {
                    return((T)Convert.ChangeType(value, typeof(T)));
                }
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("Could not fetch value for key [{0}]. Reason: {1}", key, ex.Message);
            }

            return(defaultValue);
        }
        /// <summary>
        /// Creates a web safe base64 thumbprint of some buffer.
        /// </summary>
        /// <param name="cryptoProvider">The crypto provider.</param>
        /// <param name="buffer">The buffer.</param>
        /// <returns>A string representation of a hash of the <paramref name="buffer"/>.</returns>
        public static string CreateWebSafeBase64Thumbprint(this ICryptoProvider cryptoProvider, byte[] buffer)
        {
            Requires.NotNull(cryptoProvider, "cryptoProvider");
            Requires.NotNull(buffer, "buffer");

            var hash = cryptoProvider.Hash(buffer);

            return(Utilities.ToBase64WebSafe(hash));
        }
Пример #3
0
        private async Task ProcessPassword(ISessionContext context)
        {
            var value = Encoding.ASCII.GetString(await context.Request.Body.GetBytes());

            if (string.IsNullOrWhiteSpace(value))
            {
                await ShowError(context, "You must specify a password to continue.");
                await ShowPasswordPrompt(context);

                return;
            }

            if (value.Length < 6)
            {
                await ShowError(context, "Your password must be at least 6 characters.");
                await ShowPasswordPrompt(context);

                return;
            }

            var username     = context.Session.Properties.Get("signup.username").ToString();
            var seed         = Guid.NewGuid();
            var passwordHash = m_CryptoProvider.Hash(value, seed.ToByteArray());
            var userId       = Guid.NewGuid();
            var user         = new User
            {
                Id             = userId,
                Username       = username,
                Password       = passwordHash,
                Seed           = seed,
                DateAdded      = DateTime.Now,
                IpAddress      = context.Session.ClientAddress.ToString(),
                PropertiesBlob = "{ }"
            };

            try
            {
                using (var userEngine = context.Session.GetDependency <IUserEngine>())
                {
                    userEngine.CreateUser(user);
                }
            }
            catch (Exception ex)
            {
                await ShowError(context, "There was an unknown error processing your request.  This has been logged, and the system operator has been notified.  Please try your request again later.");

                context.Session.IsLoggingOff = true;
                // Log Exception
                return;
            }

            await context.Response.Append(AnsiBuilder.Parse($"\r\n[[bg.black]][[fg.white]]Welcome {username}!\r\n"));

            context.Session.Properties.Set(SessionConstants.IsAuthenticated, true);
            context.User = user;
            await Next.OnDataReceived(context);
        }
        /// <summary>
        /// Determines whether a given thumbprint matches the actual hash of the specified buffer.
        /// </summary>
        /// <param name="cryptoProvider">The crypto provider.</param>
        /// <param name="buffer">The buffer.</param>
        /// <param name="allegedHashWebSafeBase64Thumbprint">The web-safe base64 encoding of the thumbprint that the specified buffer's thumbprint is expected to match.</param>
        /// <returns><c>true</c> if the thumbprints match; <c>false</c> otherwise.</returns>
        /// <exception cref="System.NotSupportedException">If the length of the thumbprint is not consistent with any supported hash algorithm.</exception>
        public static bool IsThumbprintMatch(this ICryptoProvider cryptoProvider, byte[] buffer, string allegedHashWebSafeBase64Thumbprint)
        {
            Requires.NotNull(cryptoProvider, "cryptoProvider");
            Requires.NotNull(buffer, "buffer");
            Requires.NotNullOrEmpty(allegedHashWebSafeBase64Thumbprint, "allegedHashWebSafeBase64Thumbprint");

            byte[] allegedThumbprint = Convert.FromBase64String(Utilities.FromBase64WebSafe(allegedHashWebSafeBase64Thumbprint));
            var    hashAlgorithm     = Utilities.GuessHashAlgorithmFromLength(allegedThumbprint.Length);

            var actualThumbprint = cryptoProvider.Hash(buffer, hashAlgorithm);

            return(Utilities.AreEquivalent(actualThumbprint, allegedThumbprint));
        }
        /// <summary>
        /// Computes the hash of the specified buffer and checks for a match to an expected hash.
        /// </summary>
        /// <param name="cryptoProvider">The crypto provider.</param>
        /// <param name="data">The data to hash.</param>
        /// <param name="expectedHash">The expected hash.</param>
        /// <param name="hashAlgorithmName">Name of the hash algorithm. If <c>null</c>, the algorithm is guessed from the length of the hash.</param>
        /// <returns>
        /// <c>true</c> if the hashes came out equal; <c>false</c> otherwise.
        /// </returns>
        internal static bool IsHashMatchWithTolerantHashAlgorithm(this ICryptoProvider cryptoProvider, byte[] data, byte[] expectedHash, string hashAlgorithmName)
        {
            Requires.NotNull(cryptoProvider, "cryptoProvider");
            Requires.NotNull(data, "data");
            Requires.NotNull(expectedHash, "expectedHash");

            if (hashAlgorithmName == null)
            {
                hashAlgorithmName = Utilities.GuessHashAlgorithmFromLength(expectedHash.Length);
            }

            byte[] actualHash = cryptoProvider.Hash(data, hashAlgorithmName);
            return(Utilities.AreEquivalent(expectedHash, actualHash));
        }
Пример #6
0
        public User GetUser(string username, string password)
        {
            var user = (from a in m_UserRepository.GetUsers()
                        where a.Username == username
                        select a).FirstOrDefault();

            if (user == null)
            {
                return(null);
            }

            var passwordHash = m_CryptoProvider.Hash(password, user.Seed.ToByteArray());

            if (user.Password != passwordHash)
            {
                return(null);
            }

            user.Properties = JsonConvert.DeserializeObject <Dictionary <string, object> >(user.PropertiesBlob);
            return(user);
        }
Пример #7
0
        /// <summary>
        /// Creates an instance of SettingsProvider with a ICryptoProvider instance
        /// </summary>
        /// <param name="cryptoProvider">CryptoProvider used for encryption and decryption</param>
        public SettingsProvider(ICryptoProvider cryptoProvider)
        {
            _cryptoProvider = cryptoProvider;

            var key = _cryptoProvider.Hash("_data");

            if (PlayerPrefs.HasKey(key))
            {
                try
                {
                    var decrypted = _cryptoProvider.Decrypt(PlayerPrefs.GetString(key));
                    _data = JsonConvert.DeserializeObject <Dictionary <string, object> >(decrypted, _serializerSettings);
                }
                catch (Exception ex)
                {
                    Debug.LogErrorFormat("Corrupt settings. Deleting. Reason: {0}", ex);

                    PlayerPrefs.DeleteKey(key);
                    _data = new Dictionary <string, object>();
                }
            }
        }
Пример #8
0
 public bool IsPasswordCorrect(User user, string password)
 {
     return(_cryptoProvider.Hash(password).Equals(user.PasswordHash));
 }