c# – Why can't I have the password hash in my seed method?

Question:

I'm trying to use my seed method below to create a user in the database when it's created:

protected override void Seed(CodingCraftMod1Ex4AuthMembershipContext context)
{
    string password = PasswordsHelper.EncodePassword("123456", System.Web.Security.MembershipPasswordFormat.Hashed);

    var user = new CustomUser
    {
        CustomUserId = Guid.NewGuid(),
        Name = "MyUser",
        CreatedOn = DateTime.Now,
        LastModified = DateTime.Now
    };

    context.CustomUsers.Add(user);
    context.SaveChanges();

    var membership = new Membership
    {
        MembershipId = Guid.NewGuid(),
        CustomUser = user,
        Password = password,
        CreatedOn = DateTime.Now,
        LastModified = DateTime.Now,
    };

    context.Memberships.Add(membership);
    context.SaveChanges();
}

But I get the following error:

Hashed or Encrypted passwords are not supported with auto-generated keys

I'm already using the machineKey element, like this:

<machineKey   validationKey="13687AD58719815734D5ECA97AADA159F4084FE994E32192243818A714DD6BC763B9F3D8AE7B3A7858A268D8EAAB37BF5031E77E5971C82BC1ACEA478C76C6CF" 
decryptionKey="A39F3B62B3CAAD3F75358197CA1D880BA3F392BE79AE4E91D2A09219D82A6978"
validation="SHA1" 
decryption="AES" />

I used this online tool to generate the keys.

Below is the custom snippet of the method that hash the password in the EncodePassword method:

case MembershipPasswordFormat.Hashed:
    HMACSHA1 hash = new HMACSHA1();
    hash.Key = HexToByte(machineKey.ValidationKey);
    encodedPassword =
        Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
    break;

Answer:

I couldn't find a way to make the hash work using my custom Membership code.

It's even obvious, but I'll leave the way around it. Instead of using the excerpt below:

string password = PasswordsHelper.EncodePassword("123456", System.Web.Security.MembershipPasswordFormat.Hashed);

I simply Hashed the password I wanted to use for the user created in the seed and put it directly in the method, as Hash:

string password = "h+V92o4VkQjWgegKgqwprJ2PUFU=";
Scroll to Top