How to programmatically change your Windows domain password using C# (.NET)

Ever wanted to write a program that would change your password for you? Why on earth would you want this? Well, imagine you have a password policy that requires you to change your password every X days. Well, maybe you like your password and think it dumb to have to keep changing it. Maybe you would forget your new password and resort to writing it down.

Ideally, you should come up with a good password to begin with, then changing it would not be really necessary. Unless of course you are under attack by the Chinese.

So, I wrote a program that changes the password in code. Moreover, it does it multiple times then the puts it back to the original. My problem solved. Here is the code for your education and amusement. Now that you know how to change your password, will you use this for purposes of good or evil? Try leaving the world a better place.

[csharp]
using System;
using System.DirectoryServices.AccountManagement;
using System.Security.Principal;
using System.Windows.Forms;

namespace KeepMyPassword
{
public partial class fKeepMyPassword : Form
{
public fKeepMyPassword()
{
InitializeComponent();
}

private void cmdChangePassword_Click(object sender, EventArgs e)
{
txtCurrentPassword.Enabled = false;
cmdChangePassword.Enabled = false;
try
{
ChangePassword(txtCurrentPassword.Text);
}
catch (Exception ex)
{
MessageBox.Show("An error occurred:" + ex.Message);
}

txtCurrentPassword.Enabled = true;
cmdChangePassword.Enabled = true;
}

private string currentPassword;
private void ChangePassword(string p)
{
var currentUser = WindowsIdentity.GetCurrent().Name;
currentPassword = p;
try
{
using (var context = new PrincipalContext(ContextType.Domain))
using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, currentUser))
{
for (int ix = 0; ix < 10; ix++)
{
var newPassword = p + (char)(((int)’a’) + ix);
user.ChangePassword(currentPassword, newPassword);
currentPassword = newPassword;
}
user.ChangePassword(currentPassword, p);
currentPassword = p;
MessageBox.Show("Password has been reset and back to original");
}
//set back to normal
}
catch (Exception ex)
{
MessageBox.Show("An error occurred:" + ex.Message + "nYour password is now: " + currentPassword);
}
}
}
}

[/csharp]

Happy Coding!

 

KeepMyPassword <- you can download the compiled exe if you wish. Needs .NET 4.0 to run.