public void DecryptFile(string sourceName, string targetName) { var sourceInfo = new FileInfo(sourceName); if (!sourceInfo.Exists) { throw new FileNotFoundException("Source File was not found or has been deleted.", sourceName); } var targetInfo = new FileInfo(targetName); if (targetInfo.Exists) { var message = string.Format("Target File \"{0}\" already exists.", targetName); throw new InvalidOperationException(message); } SBUtils.Unit.SetLicenseKey(SBUtils.Unit.BytesOfString(License)); var privateRing = new SBPGPKeys.TElPGPKeyring(); lock (typeof(SBPGPKeys.TElPGPKeyring)) { privateRing.Load(encryptionKey, signatureKey, true); } var reader = new TElPGPReader { DecryptingKeys = privateRing, VerifyingKeys = privateRing, KeyPassphrase = passphrase, }; try { using (var sourceStream = sourceInfo.OpenRead()) using (var targetStream = targetInfo.Create()) using (reader) { reader.OutputStream = targetStream; reader.DecryptAndVerify(sourceStream, 0); } } catch (Exception) { targetInfo.Refresh(); if (targetInfo.Exists) { targetInfo.Delete(); } throw; } }
private bool Decrypt(string sourceFile) { bool bSuccess = false; FileStream streamInput = null; string pgpFile = sourceFile.Replace(".pgp", ""); try { streamInput = new FileStream(sourceFile, FileMode.Open); FileStream streamOutput = new FileStream(pgpFile, FileMode.Create); try { // pgpReader TElPGPReader _pgpReader = new TElPGPReader() { KeyPassphrase = null, OutputStream = streamOutput, //assgin keyrings to reader DecryptingKeys = Keyring, VerifyingKeys = Keyring, }; _pgpReader.OnKeyPassphrase += new SBPGPStreams.TSBPGPKeyPassphraseEvent(this.pgpReader_OnKeyPassphrase); //pgpReader.Passphrase = PassPhrase; //setting PassPhrase here did not work. _pgpReader.DecryptAndVerify(streamInput, 0); bSuccess = true; } catch (Exception ex) { Task asyncTask = WriteToLogFileAsync(string.Format("Sourcefile:{0} Error:{1}", sourceFile, ex.Message)); throw; } finally { if (streamOutput != null) { streamOutput.Close(); } } } catch (Exception ex) { Task asyncTask = WriteToLogFileAsync(string.Format("Sourcefile:{0} Error:{1}", sourceFile, ex.Message)); throw; } finally { if (streamInput != null) { streamInput.Close(); } } if (bSuccess) { new FileInfo(pgpFile).LastWriteTime = new FileInfo(sourceFile).LastWriteTime; new FileInfo(pgpFile).CreationTime = new FileInfo(sourceFile).CreationTime; } return(bSuccess); }