public class GPG
{
private ILog log = LogManager.GetLogger(MethodInfo.GetCurrentMethod().DeclaringType);
private const string DEFAULT_GPG_PATH = @"C:\Program Files\GNU\GnuPG\";
private const string DECRYPT_ARGS = @"--batch --output ""{0}"" --decrypt ""{1}""";
private const string ENCRYPT_ARGS = @"--batch --output ""{0}"" --encrypt --recipient ""{2}"" ""{1}""";
private string _gpgPath;
public GPG()
{
_gpgPath = DEFAULT_GPG_PATH;
}
public string GpgPath
{
set { _gpgPath = value; }
}
public string DecryptFile(string filePath)
{
string outFile;
if (filePath.EndsWith(".gpg"))
{
outFile = filePath.Remove(filePath.Length - 4, 4);
}else
{
outFile = string.Format("{0}{1}", filePath, ".out");
}
return DecryptFile(filePath,outFile);
}
public string DecryptFile(string filePath, string outFile)
{
string args = string.Format(DECRYPT_ARGS, outFile, filePath);
ExecuteGPG(args);
return outFile;
}
public string EncryptFile(string filePath, string userId)
{
string outFile = string.Format("{0}{1}", filePath, ".gpg");
return EncryptFile(filePath, outFile, userId);
}
public string EncryptFile(string filePath, string outFile, string userId)
{
string args = string.Format(ENCRYPT_ARGS, outFile, filePath, userId);
ExecuteGPG(args);
return outFile;
}
private void ExecuteGPG(string args)
{
try
{
Process process = new Process();
string programPath = string.Format(@"""{0}""", Path.Combine(_gpgPath, "gpg.exe"));
if(!File.Exists(programPath))
{
string error = string.Format("Invalid gpg.exe path: {0}, please set GpgPath property", programPath);
log.Error(error);
throw new Exception(error);
}
log.InfoFormat("Executing: {0} {1}", programPath, args);
process.StartInfo.FileName = programPath;
//Open as readonly
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WorkingDirectory = _gpgPath;
process.Start();
StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();
log.InfoFormat("Output: {0}", output);
}
catch (Exception ex)
{
log.Error("Failed to execute gpg.exe command",ex);
throw;
}
}
}
Comments
Post a Comment