Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #region Hash
- public string HashPasswordForStorage(string password) {
- string salt;
- var hashed = EncryptOrHashNewPassword(password, out salt);
- return FormatPasswordForStorage(hashed, salt);
- }
- /// <summary>
- /// Encrypt/hash a new password with a new salt
- /// </summary>
- /// <param name="newPassword"></param>
- /// <param name="salt"></param>
- /// <returns></returns>
- protected internal string EncryptOrHashNewPassword(string newPassword, out string salt) {
- salt = GenerateSalt();
- return EncryptOrHashPassword(newPassword, salt);
- }
- protected internal static string GenerateSalt() {
- var numArray = new byte[16];
- new RNGCryptoServiceProvider().GetBytes(numArray);
- return Convert.ToBase64String(numArray);
- }
- protected internal string EncryptOrHashPassword(string pass, string salt) {
- //This is the correct way to implement this (as per the sql membership provider)
- var bytes = Encoding.Unicode.GetBytes(pass);
- var saltBytes = Convert.FromBase64String(salt);
- byte[] inArray;
- var hashAlgorithm = GetHashAlgorithm(pass);
- var algorithm = hashAlgorithm as KeyedHashAlgorithm;
- if (algorithm != null) {
- var keyedHashAlgorithm = algorithm;
- if (keyedHashAlgorithm.Key.Length == saltBytes.Length) {
- //if the salt bytes is the required key length for the algorithm, use it as-is
- keyedHashAlgorithm.Key = saltBytes;
- }
- else if (keyedHashAlgorithm.Key.Length < saltBytes.Length) {
- //if the salt bytes is too long for the required key length for the algorithm, reduce it
- var numArray2 = new byte[keyedHashAlgorithm.Key.Length];
- Buffer.BlockCopy(saltBytes, 0, numArray2, 0, numArray2.Length);
- keyedHashAlgorithm.Key = numArray2;
- }
- else {
- //if the salt bytes is too short for the required key length for the algorithm, extend it
- var numArray2 = new byte[keyedHashAlgorithm.Key.Length];
- var dstOffset = 0;
- while (dstOffset < numArray2.Length) {
- var count = Math.Min(saltBytes.Length, numArray2.Length - dstOffset);
- Buffer.BlockCopy(saltBytes, 0, numArray2, dstOffset, count);
- dstOffset += count;
- }
- keyedHashAlgorithm.Key = numArray2;
- }
- inArray = keyedHashAlgorithm.ComputeHash(bytes);
- }
- else {
- var buffer = new byte[saltBytes.Length + bytes.Length];
- Buffer.BlockCopy(saltBytes, 0, buffer, 0, saltBytes.Length);
- Buffer.BlockCopy(bytes, 0, buffer, saltBytes.Length, bytes.Length);
- inArray = hashAlgorithm.ComputeHash(buffer);
- }
- return Convert.ToBase64String(inArray);
- }
- protected internal string FormatPasswordForStorage(string pass, string salt) {
- return salt + pass;
- }
- protected internal HashAlgorithm GetHashAlgorithm(string password) {
- var alg = HashAlgorithm.Create("HMACSHA256");
- if (alg == null) {
- throw new InvalidOperationException("The hash algorithm specified " + Membership.HashAlgorithmType + " cannot be resolved");
- }
- return alg;
- }
- #endregion
Add Comment
Please, Sign In to add comment