Changing passwordFormat from Encrypted to Hashed

前端 未结 4 1445
礼貌的吻别
礼貌的吻别 2020-12-08 16:37

I\'m finding surprisingly little information on converting an existing database from Encrypted passwords to Hashed passwords. (I was able to find a bit more information on c

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 17:08

    Greg's solution is a good start, but it won't affect existing users. The SqlMembershipProvider protects existing users and passwords by storing the PasswordFormat (0=clear, 1=Hashed, 2=Encrypted) in the table along with passwords. Changing the provider password format only affects inserts to the user tables. In order to convert existing users' passwords to Hashed, you have to change the PasswordFormat parameter for each entry. Here is a simple way to do this:

    void HashAllPasswords()
    {
        var clearProvider = Membership.Providers["SqlProvider_Clear"];
        var hashedProvider = Membership.Providers["SqlProvider_Hashed"];
        int dontCare;
        if (clearProvider == null || hashedProvider == null) return;
        var passwords = clearProvider.GetAllUsers(0, int.MaxValue, out dontCare)
            .Cast().ToDictionary(u => u.UserName, u => u.GetPassword());
    
        using (var conn = new SqlConnection(
               ConfigurationManager.ConnectionStrings[0].ConnectionString))
        {
            conn.Open();
            using (var cmd = new SqlCommand(
                   "UPDATE [aspnet_Membership] SET [PasswordFormat]=1", conn))
                cmd.ExecuteNonQuery();
        }
    
        foreach (var entry in passwords)
        {
            var resetPassword = hashedProvider.ResetPassword(entry.Key, null);
            hashedProvider.ChangePassword(entry.Key, resetPassword, entry.Value);
        }
    }
    

提交回复
热议问题