You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于C#实现BitLocker自定义密码加密及恢复密钥存储问题求助

Solution for Automating BitLocker Encryption with Custom Password in C#

Hey Sara, let's work through this BitLocker automation problem you're facing! The issue with your initial cmd approach is that passing a custom password directly in the command line isn't just clunky—it's also insecure. But we can fix this in C# by properly leveraging the manage-bde tool with secure input handling.

Key Background on manage-bde

To set a custom password and save the recovery key, we need two core steps with manage-bde:

  1. Enable BitLocker encryption on the drive and add a password protector
  2. Export the recovery key to your specified directory

The trick is to avoid hardcoding or passing the password as a visible command-line argument—instead, we'll send it securely via the process's standard input.

Complete C# Implementation

This code will handle drive validation, secure password input, encryption initiation, and recovery key saving:

using System;
using System.Diagnostics;
using System.IO;

class BitLockerTool
{
    static void Main(string[] args)
    {
        // Configure these values to match your needs
        string targetDrive = "E:"; // Replace with your external drive letter
        string userPassword = "YourStrongPassword123!"; // Your custom password
        string recoveryKeyFolder = @"C:\BitLockerRecoveryKeys"; // Target directory for keys

        try
        {
            // Create recovery key directory if it doesn't exist
            if (!Directory.Exists(recoveryKeyFolder))
            {
                Directory.CreateDirectory(recoveryKeyFolder);
            }

            // Step 1: Start encryption with custom password
            bool encryptionStarted = StartEncryptionWithPassword(targetDrive, userPassword);
            
            if (encryptionStarted)
            {
                // Step 2: Save recovery key to specified folder
                bool keySaved = SaveRecoveryKey(targetDrive, recoveryKeyFolder);
                
                Console.WriteLine(keySaved 
                    ? "Success! Drive encrypted and recovery key saved." 
                    : "Encryption worked, but recovery key export failed.");
            }
            else
            {
                Console.WriteLine("Failed to start BitLocker encryption.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }

    static bool StartEncryptionWithPassword(string driveLetter, string password)
    {
        var processInfo = new ProcessStartInfo
        {
            FileName = "manage-bde.exe",
            Arguments = $"-on {driveLetter} -protectors -add {driveLetter} -password",
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true,
            Verb = "runas" // Requires admin privileges
        };

        using (var process = Process.Start(processInfo))
        {
            // Send password twice (manage-bde prompts for confirmation)
            process.StandardInput.WriteLine(password);
            process.StandardInput.WriteLine(password);
            process.StandardInput.Close();

            process.WaitForExit();
            return process.ExitCode == 0;
        }
    }

    static bool SaveRecoveryKey(string driveLetter, string saveFolder)
    {
        string keyFile = Path.Combine(saveFolder, $"RecoveryKey_{driveLetter.TrimEnd(':')}.txt");
        
        var processInfo = new ProcessStartInfo
        {
            FileName = "manage-bde.exe",
            Arguments = $"-protectors -get {driveLetter} -type recoverypassword > \"{keyFile}\"",
            UseShellExecute = false,
            CreateNoWindow = true,
            Verb = "runas"
        };

        using (var process = Process.Start(processInfo))
        {
            process.WaitForExit();
            return process.ExitCode == 0 && File.Exists(keyFile);
        }
    }
}

Critical Notes for Production Use

  • Admin Rights: BitLocker operations require elevated privileges—this is why we set Verb = "runas" to prompt for admin access.
  • Password Security: Never hardcode passwords in production! Replace the hardcoded password with a secure input method (like a masked text box in a UI or a secure prompt).
  • Drive Checks: Add validation to ensure the target drive is an external, unencrypted drive using manage-bde -status {driveLetter} if needed.
  • Error Details: For debugging, read the StandardOutput and StandardError streams from the manage-bde process to get specific failure messages.

How It Works

  1. The StartEncryptionWithPassword method runs manage-bde to enable encryption and add a password protector. It sends the password twice (to match manage-bde's confirmation prompt) via secure standard input.
  2. The SaveRecoveryKey method extracts the recovery password and saves it to your specified folder in a named text file for easy reference.

This should solve your problem of automating custom password encryption and recovery key storage!

内容的提问来源于stack exchange,提问作者Sara Vignali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:16:00