基于C#实现BitLocker自定义密码加密及恢复密钥存储问题求助
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:
- Enable BitLocker encryption on the drive and add a password protector
- 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
StandardOutputandStandardErrorstreams from themanage-bdeprocess to get specific failure messages.
How It Works
- The
StartEncryptionWithPasswordmethod runsmanage-bdeto enable encryption and add a password protector. It sends the password twice (to matchmanage-bde's confirmation prompt) via secure standard input. - The
SaveRecoveryKeymethod 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

