AuthenticationExample.Web.Controllers.Cryptography.RandomString C# (CSharp) Method

RandomString() public static method

public static RandomString ( int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ) : string
length int
allowedChars string
return string
		public static string RandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
		{
			if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
			if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");

			const int byteSize = 0x100;
			var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
			if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));

			// Guid.NewGuid and System.Random are not particularly random. By using a
			// cryptographically-secure random number generator, the caller is always
			// protected, regardless of use.
			using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
			{
				var result = new StringBuilder();
				var buf = new byte[128];
				while (result.Length < length)
				{
					rng.GetBytes(buf);
					for (var i = 0; i < buf.Length && result.Length < length; ++i)
					{
						// Divide the byte into allowedCharSet-sized groups. If the
						// random value falls into the last group and the last group is
						// too small to choose from the entire allowedCharSet, ignore
						// the value in order to avoid biasing the result.
						var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
						if (outOfRangeStart <= buf[i]) continue;
						result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
					}
				}
				return result.ToString();
			}
		}
	}

Usage Example

Beispiel #1
0
        public ActionResult Start(StartRegistrationModel startRegistrationModel)
        {
            if (_repository.GetAll <User>().Any(x => x.Username == startRegistrationModel.Username))
            {
                ModelState.AddModelError("Username", "Username is already in use");
            }

            if (_repository.GetAll <User>().Any(x => x.EmailAddress == startRegistrationModel.EmailAddress))
            {
                ModelState.AddModelError("EmailAddress", "Email address is already in use");
            }

            if (ModelState.IsValid)
            {
                var verificationCode = Cryptography.RandomString(12);
                var user             = new Registration
                {
                    Id               = Guid.NewGuid(),
                    Username         = startRegistrationModel.Username,
                    EmailAddress     = startRegistrationModel.EmailAddress,
                    Password         = Cryptography.Hash(startRegistrationModel.Password),
                    Expires          = DateTime.UtcNow.AddDays(3),
                    VerificationCode = Cryptography.Hash(verificationCode)
                };

                var registrationConfirmation = new RegistrationConfirmation
                {
                    Username         = startRegistrationModel.Username,
                    EmailAddress     = startRegistrationModel.EmailAddress,
                    VerificationCode = verificationCode
                };
                _confirmationEmailer.Send(registrationConfirmation);

                _repository.SaveOrUpdate(user);

                return(RedirectToAction(
                           "Complete", "Registration", new { startRegistrationModel.Username, startRegistrationModel.EmailAddress }));
            }

            return(View(startRegistrationModel));
        }