C# – Change Admin Password and Add Encrypted Reg Key

email me

Just a few things to note:

— Always store your source code in a secure location.

— If you want to use the encrypted pw in the registry,
I recommend naming the reg key itself to something
obscure (not AdminPassword).

— Don’t forget to change the permutations for every
new password.

— And, only pass the encrypted password between your
compiled apps. Code the application to decrypt the
password.

— I have added all the methods together here—for demo purposes—you want to
separate the encrypt and decrypt into two EXEs.

Screenshot of an encrypted reg key

 

using System;
using System.IO;                    // MemoryStream
using System.Security.Cryptography; // used by aes
using System.Text;                  // used by Encoding
using Microsoft.Win32;              // used by Registry
using System.Windows.Forms;         // used by Messagebox
using System.Diagnostics;           // used by Process

namespace SecurePassword
{
    class ResetPassword
    {       

        public static class Global
        {
            // Set password
            public const string strPassword = "LetMeIn99$";

            // Testing
            //public const String strPassword = "ABCZYZabczyx123890!@\"\\#/:;<>?$%^&*()-_+={}[]";

            // set permutations
            public const string strPermutation = "ouiveyxaqtd";
            public const int bytePermutation1 = 0x19;
            public const int bytePermutation2 = 0x59;
            public const int bytePermutation3 = 0x17;
            public const int bytePermutation4 = 0x41;

            // set reg value
            public const string strRegHive = "HKEY_LOCAL_MACHINE";
            public const string strRegKey = @"SOFTWARE\ZWTValue\";
            public const string strRegPath = strRegHive + @"\" + strRegKey;
            public const string strRegVal = "ZWTValue1";          

        }




        public static void Main(string[] args)
        {
            {

    // BEGIN - ENCRYPT PASSWORD
            
                // encrypt
                string strEncrypted = (Encrypt(Global.strPassword));
    
    // END - ENCRYPT PASSWORD




    // BEGIN - ADD ENCRYPTED PASSWORD TO REGISTRY 

                // try set reg value
                try
                {
                    //requires admin access
                    Registry.SetValue(Global.strRegPath, Global.strRegVal, strEncrypted, RegistryValueKind.String);
                    // reference https://msdn.microsoft.com/en-us/library/3dwk5axy(v=vs.110).aspx                

                }

                // catch if there is an error in encrypt
                // ex.Exception
                catch (Exception)
                {
                    //MessageBox.Show(ex.ToString());
                }
    // END - ADD ENCRYPTED PASSWORD TO REGISTRY




    // BEGIN - CHANGE PASSWORD

                // try to change password
                // set properties for process                       
                // requires admin access
                ProcessStartInfo cmdProcess = new ProcessStartInfo("net.exe", "user administrator \"" + Global.strPassword + "\"");
                cmdProcess.RedirectStandardOutput = false;
                cmdProcess.WindowStyle = ProcessWindowStyle.Hidden; // hide window
                cmdProcess.UseShellExecute = true;
                Process checkProcess = null;

                try
                {
                    // launch command
                    checkProcess = Process.Start(cmdProcess);
                    checkProcess.WaitForExit();
                    // reference https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.110).aspx

                    ////MessageBox.Show(checkProcess.ExitCode.ToString());                   

                    if (checkProcess.ExitCode == 0)
                    {

                        // MessageBox.Show("  Local admin password was reset!");
                        // reference https://msdn.microsoft.com/en-us/library/system.environment.exitcode(v=vs.110).aspx
                    }
                }


                catch (Exception)
                // ex.Exception
                {
                    // MessageBox.Show(ex.ToString());
                }

    // END - CHANGE PASSWORD




    // BEGIN - READ PASSWORD FROM REGISTRY

                string strRegTest = "false";

                // sets the encrypted pw value, to What the reg value should be
                string strEncryptedRegValue = strEncrypted;                

                // try opening reg key
                try
                    {
                        // return encrypted key from registry
                        RegistryKey returnKey = Registry.LocalMachine.OpenSubKey(Global.strRegKey);

                        string rkValue = returnKey.GetValue(Global.strRegVal).ToString();
                        //reference https://msdn.microsoft.com/en-us/library/z9f66s0a(v=vs.110).aspx
                        returnKey.Close();

                    if (returnKey != null)
                            
                         // try testing encrypted key with encrypted pw value
                         try
                               {
                                    if (strEncrypted == rkValue)
                                {
                                    //MessageBox.Show("True");
                                    strRegTest = "true";
                                }

                                    else

                                 {
                                //MessageBox.Show("False");
                                strRegTest = "false";
                                }
                            }
                        // will catch errors reading values
                        catch (Exception)
                        {

                        }                   

                }
                // will catch reg error where no key exists
                catch (Exception)
                {
                    //MessageBox.Show("There is no value!");
                    strRegTest = "false";
                }

                 // decrypt
                 //string strDecrypted = (Decrypt(strEncrypted));
                 string strDecrypted = (Decrypt(rkValue.ToString()));
                 //MessageBox.Show(strDecrypted);

    // END - READ PASSWORD FROM REGISTRY




    // BEGIN OUTPUT
                                
                MessageBox.Show("Original: " + Global.strPassword + "\n\n" + 
                               "Encrypted: " + strEncrypted + "\n\n" + 
                               "Decrypted: " + strDecrypted + "\n\n" + 
                               "Reg Test (is key the same?): " + strRegTest);
    // END OUTPUT
               
                
            }
                    
        }
        
        
        
        
        // encoding
        public static string Encrypt(string strData)
        {
            return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(strData)));
            // reference https://msdn.microsoft.com/en-us/library/ds4kkd55(v=vs.110).aspx

        }


        // decoding
        public static string Decrypt(string strData)
        {
            return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(strData)));
            // reference https://msdn.microsoft.com/en-us/library/system.convert.frombase64string(v=vs.110).aspx

        }

        // encrypt
        public static byte[] Encrypt(byte[] strData)
        {
            PasswordDeriveBytes passbytes =
            new PasswordDeriveBytes(Global.strPermutation,
            new byte[] { Global.bytePermutation1,
                         Global.bytePermutation2,
                         Global.bytePermutation3,
                         Global.bytePermutation4
            });

            MemoryStream memstream = new MemoryStream();
            Aes aes = new AesManaged();
            aes.Key = passbytes.GetBytes(aes.KeySize/8);
            aes.IV = passbytes.GetBytes(aes.BlockSize/8);

            CryptoStream cryptostream = new CryptoStream(memstream,
            aes.CreateEncryptor(), CryptoStreamMode.Write);
            cryptostream.Write(strData, 0, strData.Length);
            cryptostream.Close();
            return memstream.ToArray();
        }

        // decrypt
        public static byte[] Decrypt(byte[] strData)
        {
            PasswordDeriveBytes passbytes =
            new PasswordDeriveBytes(Global.strPermutation,
            new byte[] { Global.bytePermutation1,
                         Global.bytePermutation2,
                         Global.bytePermutation3,
                         Global.bytePermutation4
            });

            MemoryStream memstream = new MemoryStream();
            Aes aes = new AesManaged();
            aes.Key = passbytes.GetBytes(aes.KeySize/8);
            aes.IV = passbytes.GetBytes(aes.BlockSize/8);

            CryptoStream cryptostream = new CryptoStream(memstream,
            aes.CreateDecryptor(), CryptoStreamMode.Write);
            cryptostream.Write(strData, 0, strData.Length);
            cryptostream.Close();
            return memstream.ToArray();
        }
        // reference 
        // https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
        // https://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx
    }
}