Search code examples
c#winformsbitlocker

c# Bitlocker enter password programmatically


I have a disk encrypted with Windows BitLocker. How can I unlock the drive with the password I enter in Winforms. If I can achieve this, I will be able to use the documents on the encrypted drive in Winforms.

I tried the steps at this address, but I could only access the status of BitLocker, nothing else.


Solution

  • using System.Management;
    
    namespace WinForms
    {
        public class BitLocker
        {
            private readonly string _computerIp;
    
            public BitLocker(string computerIp)
            {
                _computerIp = computerIp;
            }
    
            /// <summary>
            /// Simple Usage for localhost:
            /// var bitlocker = new BitLocker("localhost");
            /// var result = bitlocker.UnlockWithPassphrase("D:", "password");
            /// </summary>
            /// <param name="driveLetter"></param>
            /// <param name="passphrase"></param>
            /// <returns></returns>
    
            public object UnlockWithPassphrase(string driveLetter, string passphrase)
            {
                object result = null;
                const string wmiNamespace = "\\\\{0}\\root\\CIMV2\\Security\\MicrosoftVolumeEncryption";
                var scope = new ManagementScope(string.Format(wmiNamespace, _computerIp));
    
                var query = new ObjectQuery("SELECT * FROM Win32_EncryptableVolume");
                var searcher = new ManagementObjectSearcher(scope, query);
    
                var allVolumes = searcher.Get();
                foreach (var o in allVolumes)
                {
                    var volume = (ManagementObject) o;
                    if (volume.Properties["DriveLetter"].Value.ToString() != driveLetter) continue;
                    object[] methodArgs = { passphrase };
                    result = volume.InvokeMethod("UnlockWithPassphrase", methodArgs);
                }
                return result;
            }
        }
    }
    

    Note that it requires administrator rights.