using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace dpapicmd { class Program { static void showHelp(string err = null) { if (err != null) { var color = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkRed; Console.Error.WriteLine("Error: " + err + "\r\n"); Console.ForegroundColor = color; } Console.Error.WriteLine("dpapicmd [/user] [/decrypt] [/utf8] [/entropy:] {/clipboard|}"); Console.Error.WriteLine("Text is read as Base64 bytes unless /utf8 is used. Decrypted input and encrypted output is always Base64."); Environment.Exit(1); } static bool user = false; static bool dec = false; static bool utf8 = false; static bool clip = false; static string entropy = null; static string text; [STAThread] static void Main(string[] args) { if (args.Length == 0 || args[0] == "/?") { showHelp(); } Array.Reverse(args); var argsl = new List(args); var texts = argsl.FindAll(s => !s.StartsWith("/")); if (texts.Count > 1) { showHelp("Too many inputs."); } text = texts.Count == 0 ? null : texts[0]; var options = new Stack(argsl.FindAll(s => s.StartsWith("/"))); while (options.Count > 0){ var opt = options.Pop(); if (opt.Length < 4) { showHelp("Invalid option: " + opt + "."); } processOption(opt); } if ((clip && dec) || (clip && !dec && text == null)) { if (options.Count != 0) { showHelp("Cannot specify /clipboard and provide input text."); } text = System.Windows.Forms.Clipboard.GetText(); if (dec) text = text.Trim(); if (string.IsNullOrEmpty(text)) { showHelp("No text on clipboard."); } } else { if (options.Count != 0) { showHelp("Too many arguments."); } } try { var entBytes = entropy == null ? null : utf8 ? Encoding.UTF8.GetBytes(entropy) : Convert.FromBase64String(entropy); var target = (utf8 & !dec) ? Encoding.UTF8.GetBytes(text) : Convert.FromBase64String(text); var res = dec ? ProtectedData.Unprotect(target, entBytes, user ? DataProtectionScope.CurrentUser : DataProtectionScope.LocalMachine) : ProtectedData.Protect(target, entBytes, user ? DataProtectionScope.CurrentUser : DataProtectionScope.LocalMachine); var strout = (utf8 & dec) ? Encoding.UTF8.GetString(res) : Convert.ToBase64String(res); if (clip) { System.Windows.Forms.Clipboard.SetText(strout); Console.WriteLine("Output copied to clipboard."); } else { Console.WriteLine(strout); } } catch(Exception ex) { showHelp(ex.ToString()); } } static void processOption(string opt) { switch(opt.ToLowerInvariant().Substring(0,4)){ case "/use": user = true; break; case "/dec": dec = true; break; case "/utf": utf8 = true; break; case "/ent": var col = opt.IndexOf(':'); if (col == -1 || col == opt.Length - 1) showHelp(); entropy = opt.Substring(col + 1); break; case "/cli": clip = true; break; default: showHelp("Unknown option: " + opt + "."); break; } } } }