Skip to content

Instantly share code, notes, and snippets.

@khurramkhang
Last active October 31, 2017 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khurramkhang/f279284f2aecbed80ac1bbafe046c945 to your computer and use it in GitHub Desktop.
Save khurramkhang/f279284f2aecbed80ac1bbafe046c945 to your computer and use it in GitHub Desktop.
Migrate to ASP.Net Identity
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNet.Identity;
namespace MySite.Business.Identity
{
public class SqlPasswordHasher : PasswordHasher
{
public override string HashPassword(string password)
{
return base.HashPassword(password);
}
public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
{
string[] passwordProperties = hashedPassword.Split('|');
if (passwordProperties.Length != 3)
{
return base.VerifyHashedPassword(hashedPassword, providedPassword);
}
else
{
string passwordHash = passwordProperties[0];
int passwordformat = 1;
string salt = passwordProperties[2];
if (String.Equals(EncryptPassword(providedPassword, passwordformat, salt), passwordHash,
StringComparison.CurrentCultureIgnoreCase))
{
return PasswordVerificationResult.SuccessRehashNeeded;
}
else
{
return PasswordVerificationResult.Failed;
}
}
}
private string EncryptPassword(string pass, int passwordFormat, string salt)
{
if (passwordFormat == 0)
return pass;
var bPassword = Encoding.Unicode.GetBytes(pass);
var bSalt = Convert.FromBase64String(salt);
byte[] bRet = null;
if (passwordFormat != 1) return Convert.ToBase64String(bRet);
var hashAlgorithm = HashAlgorithm.Create("HMACSHA512");
if (hashAlgorithm is KeyedHashAlgorithm)
{
var keyedHashAlgorithm = (KeyedHashAlgorithm)hashAlgorithm;
if (keyedHashAlgorithm.Key.Length == bSalt.Length)
{
keyedHashAlgorithm.Key = bSalt;
}
else if (keyedHashAlgorithm.Key.Length < bSalt.Length)
{
var bKey = new byte[keyedHashAlgorithm.Key.Length];
Buffer.BlockCopy(bSalt, 0, bKey, 0, bKey.Length);
keyedHashAlgorithm.Key = bKey;
}
else
{
var bKey = new byte[keyedHashAlgorithm.Key.Length];
for (var iter = 0; iter < bKey.Length;)
{
var len = Math.Min(bSalt.Length, bKey.Length - iter);
Buffer.BlockCopy(bSalt, 0, bKey, iter, len);
iter += len;
}
keyedHashAlgorithm.Key = bKey;
}
bRet = keyedHashAlgorithm.ComputeHash(bPassword);
}
else
{
byte[] bAll = new byte[bSalt.Length + bPassword.Length];
Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
Buffer.BlockCopy(bPassword, 0, bAll, bSalt.Length, bPassword.Length);
bRet = hashAlgorithm.ComputeHash(bAll);
}
return Convert.ToBase64String(bRet);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment