0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

.NET(C#)でファイル暗号化・復号化ツールを作ったのでメモ

Last updated at Posted at 2020-11-23

GitHubに上げています。

ただ、勉強用に作成したものなので、実務などでは使用しないで下さい
暗号化処理の実装とか、バイナリファイルの読込・書込、タプルやディクショナリを勉強したり、GitHubへの反映の仕方を知りたかったのも動機です。

開発環境は以下の通りです。

  • NET 5.0
  • C#
  • Visual Studio Community for Mac
  • macOS Mojave

・更新履歴
11/23 新規公開
11/25 リファクタリングの結果などを追記

個人的に気になったところ

Dictionary初期化の書き方

こんな風に書く。

private static Dictionary<string, string> argConst = new Dictionary<string, string>
{
	{ "key1", "value1" },
	{ "key2", "value2" }
};

StreamReader, StreamWriterはテキストの読み書きに使う

.NETのドキュメントに書いてある通り、それぞれ基底クラスがTextReaderTextWriterという名前の通り、テキストを扱う。

バイナリファイルは、BinaryReaderBinaryWriterを使う。この辺りで結構はまった。

BinaryWriterだと以下のように書く。

//write decrypted data to file
using (BinaryWriter binaryWriter = new BinaryWriter(new FileStream(outputFile, FileMode.Create)))
{
	foreach (byte b in byteArray)
	binaryWriter.Write(b);
}

CryptoStreamを使用している場合、BinaryReaderのLengthが取れなかった。seekができないようで、要するに今どの場所を読み取っているかという情報が取れないらしい。

なので、復号化処理で入力データのseekが終了しているかどうかは、EndOfStreamExceptionの発生を例外処理で補足する方法しかできなかった。
→ CopyToを使うことで一応回避(但し、メモリを使うので注意)。
あと、usingをすっきりさせた。(2020/11/25追記)

using (FileStream   fileStream   = new FileStream(inputFile, FileMode.Open))
using (CryptoStream cryptoStream = new CryptoStream(fileStream, transform, CryptoStreamMode.Read))
using (MemoryStream memory       = new MemoryStream())
using (BinaryWriter binaryWriter = new BinaryWriter(new FileStream(outputFile, FileMode.Create)))
	{
		//Read decrypted data into memory
		cryptoStream.CopyTo(memory);
		byte[] decryptBytes = memory.ToArray();

		//write decrypted data to file
		binaryWriter.Write(decryptBytes);

	}

Rijndael = AESという認識だったので、Rijndaelクラスを使用したが、Aesクラスもあるようで、Microsoftのドキュメント(英語)では後者を使用すべきと書かれている…。

You should use the Aes algorithm instead of Rijndael.

Rijndael Class

実際、MSのドキュメントでは、Aes aes = Aes.Create()のように、Aes.CreateのFactoryが使用されている。

ちなみに、日本語サイトは機械翻訳のようで、意味が全然理解できないくらい文章が変でした。

まぁ今回はC#の自習でしたが、実務で暗号化が必要な時は、基本的には自作しない方が無難だと思います。

以上です。

0
0
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?