/// <summary> /// 指定されたファイルを復号化して、指定されたファイルに上書き保存します。 /// </summary> /// <param name="source">復号化するファイル名。</param> /// <param name="destination">復号化先のファイル名。</param> /// <param name="password">パスワード。</param> public static void Decrypt(string source, string destination, string password) { using (var decryptor = new Decryptor(source, password)) using (var outputStream = new FileStream(destination, FileMode.Create, FileAccess.Write)) { decryptor.Decrypt(outputStream); } }
/// <summary> /// 暗号化されたファイルを復号化して、末尾にテキストを追加し、再度暗号化して上書き保存します。 /// </summary> /// <param name="fileName">テキストを追加するファイル名。</param> /// <param name="text">追加するテキスト。</param> /// <param name="password">パスワード。</param> /// <param name="encoding">テキストのエンコーディング。</param> public static void AppendTextToFile(string fileName, string text, string password, Encoding encoding) { byte[] buffer = null; long decryptedSize = 0; int appendSize = encoding.GetByteCount(text) + Environment.NewLine.Length; // 復号化したファイルの内容を読み込みます。 if (File.Exists(fileName)) { var fileInfo = new FileInfo(fileName); int fileSize = (int)fileInfo.Length; // MemoryStreamに指定するcapacityは、復号後の予想サイズに、 // 後で文字列textを追加することを考慮した長さを加えています。 // 復号後の予想サイズは、暗号化されたファイルが圧縮されているため概算です。 int capacity = (fileSize * 3) / 2 + appendSize; using (var outputStream = new MemoryStream(capacity)) using (var decryptor = new Decryptor(fileName, password)) { decryptor.Decrypt(outputStream); buffer = outputStream.GetBuffer(); decryptedSize = outputStream.Length; } } // 読み込んだ内容に指定された文字列を追加して、暗号化して保存します。 using (var inputStream = new MemoryStream()) using (var streamWriter = new StreamWriter(inputStream, encoding)) { if (buffer != null) { streamWriter.BaseStream.Write(buffer, 0, (int)decryptedSize); } streamWriter.WriteLine("{0}", text); streamWriter.Flush(); inputStream.Seek(0, SeekOrigin.Begin); using (var encryptor = new Encryptor(fileName, password)) { encryptor.Encrypt(inputStream); } } }
/// <summary> /// 指定されたストリームを復号化して、指定されたストリームに出力します。 /// </summary> /// <param name="inputStream">入力ストリーム。</param> /// <param name="outputStream">出力ストリーム。</param> /// <param name="password">パスワード。</param> public static void Decrypt(Stream inputStream, Stream outputStream, string password) { using (var decryptor = new Decryptor(inputStream, password)) { decryptor.Decrypt(outputStream); } }