【C#】処理を共通化するという考え方

暗号化・複合化処理を文字列、ファイルを別々にコードを書いているため共通化します。

コードの共通部分を抜き出して共通化しておくことで新規に追加実装する部分は拡張部のみにすることもできます。

今回、共通化するコードは以下のリンク先にある記事で利用したコードの共通部分を抜き出して共通化します。




【C#】ファイルの暗号化・複合化を行う。【AES暗号化】

Encode → EncodeString

Decode → DecodeString

 

【C#】文字列の暗号化・複合化を行う。【AES暗号化】

Encode → EncodeFile

Decode → DecodeFile

 

コードを共通化することで、拡張する関数の実装が簡素化します。


using System;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;

namespace TestCode.Utility
{
    public class AesUtil
    {
        /// <summary>
        /// 共有キー
        /// </summary>
        private const string AES_KEY = "-SENJU MURAMASA-";

        /// <summary>
        /// バッファサイズ
        /// </summary>
        private const int BUFFER_SIZE = 1024 * 4;

        /// <summary>
        /// 共有キービットサイズ
        /// </summary>
        private const int KEY_SIZE = 128;

        /// <summary>
        /// 暗号操作のビットサイズ
        /// </summary>
        private const int BLOCK_SIZE = 128;

        /// <summary>
        /// 暗号化(文字列) - 入力・出力メモリストリームを共通関数へ渡す
        /// </summary>
        /// <param name="value">暗号化する文字列</param>
        /// <returns>暗号化した文字列</returns>
        static public string EncodeString(string value)
        {
            // 入力ストリーム
            using (MemoryStream inMs = new MemoryStream(Encoding.UTF8.GetBytes(value)))
            {
                // 出力ストリーム
                using (MemoryStream outMs = new MemoryStream())
                {
                    // 共通関数呼び出し
                    AesUtil.Encode(inMs, outMs);

                    // BASE64エンコードして返す
                    return Convert.ToBase64String(outMs.ToArray());
                }
            }
        }

        /// <summary>
        /// 複合化(文字列) - 入力・出力メモリストリームを共通関数へ渡す
        /// </summary>
        /// <param name="value">暗号化されている文字列</param>
        /// <returns>複合化された文字列</returns>
        static public string DecodeString(string value)
        {
            // 暗号化文字列ストリーム生成(BASE64でコード)
            using (MemoryStream inMs = new MemoryStream(Convert.FromBase64String(value), false))
            {
                // 出力ストリーム
                using (MemoryStream outMs = new MemoryStream())
                {
                    // 共通関数呼び出し
                    AesUtil.Decode(inMs, outMs);

                    // バイナリデータを文字列変換して返す
                    return Encoding.UTF8.GetString(outMs.ToArray());
                }
            }
        }

        /// <summary>
        /// 暗号化(ファイル) - 入力・出力ファイルストリームを共通関数へ渡す
        /// </summary>
        /// <param name="src">入力ファイルパス</param>
        /// <param name="dst">出力ファイルパス</param>
        static public void EncodeFile(string src, string dst)
        {
            // 入力ファイルストリーム
            using (FileStream inFs = new FileStream(src, FileMode.Open, FileAccess.Read))
            {
                // 出力ファイルストリーム
                using (FileStream outFs = new FileStream(dst, FileMode.Create, FileAccess.Write))
                {
                    // 共通関数呼び出し
                    AesUtil.Encode(inFs, outFs);
                }
            }
        }

        /// <summary>
        /// 複合化(ファイル) - 入力・出力ファイルストリームを共通関数へ渡す
        /// </summary>
        /// <param name="src">入力ファイルパス</param>
        /// <param name="dst">出力ファイルパス</param>
        static public void DecodeFile(string src, string dst)
        {
            // 入力ファイルストリーム
            using (FileStream inFs = new FileStream(src, FileMode.Open, FileAccess.Read))
            {
                // 出力ファイルストリーム
                using (FileStream outFs = new FileStream(dst, FileMode.Create, FileAccess.Write))
                {
                    // 共通関数呼び出し
                    AesUtil.Decode(inFs, outFs);
                }
            }
        }

        /// <summary>
        /// 暗号化(共通関数)- 暗号化に共通するコードを抜き出した関数
        /// </summary>
        /// <param name="src">入力ストリーム</param>
        /// <param name="dst">出力ストリーム</param>
        static private void Encode(Stream src, Stream dst)
        {
            // 高度暗号化標準 (AES) 
            using (AesManaged aes = new AesManaged())
            {
                // AESインスタンスのパラメータ設定
                aes.KeySize = KEY_SIZE;
                aes.BlockSize = BLOCK_SIZE;
                aes.Mode = CipherMode.CBC;
                aes.Key = Encoding.UTF8.GetBytes(AES_KEY);

                // 初期化ベクター(IV)の生成
                aes.GenerateIV();

                // 暗号化オブジェクト生成
                ICryptoTransform ct = aes.CreateEncryptor(aes.Key, aes.IV);

                // 初期化ベクター(IV)書き込み
                dst.Write(aes.IV, 0, aes.IV.Length);

                // 暗号変換のストリーム(暗号化)
                using (CryptoStream cs = new CryptoStream(dst, ct, CryptoStreamMode.Write))
                {
                    // Deflateアルゴリズムを使用したストリーム(圧縮)
                    using (DeflateStream ds = new DeflateStream(cs, CompressionMode.Compress))
                    {
                        byte[] buf = new byte[BUFFER_SIZE];
                        for (int size = src.Read(buf, 0, buf.Length); size > 0; size = src.Read(buf, 0, buf.Length))
                        {
                            // 出力ファイルへ書き込み(圧縮→暗号化→書き込み)
                            ds.Write(buf, 0, size);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 複合化(共通関数)- 複合化に共通するコードを抜き出した関数
        /// </summary>
        /// <param name="src">入力ストリーム</param>
        /// <param name="dst">出力ストリーム</param>
        static public void Decode(Stream src, Stream dst)
        {
            // 高度暗号化標準(AES)
            using (AesManaged aes = new AesManaged())
            {
                // AESインスタンスのパラメータ設定
                aes.KeySize = KEY_SIZE;
                aes.BlockSize = BLOCK_SIZE;
                aes.Mode = CipherMode.CBC;
                aes.Key = Encoding.UTF8.GetBytes(AES_KEY);

                // 初期化ベクター(IV)読込
                byte[] iv = new byte[aes.IV.Length];
                src.Read(iv, 0, iv.Length);
                aes.IV = iv;

                // 複合化オブジェクト生成
                ICryptoTransform ct = aes.CreateDecryptor(aes.Key, aes.IV);

                // 暗号変換のストリーム(複合化)
                using (CryptoStream cs = new CryptoStream(src, ct, CryptoStreamMode.Read))
                {
                    // Deflateアルゴリズムを使用したストリーム(圧縮解除)
                    using (DeflateStream ds = new DeflateStream(cs, CompressionMode.Decompress))
                    {
                        // 複合化した結果を書き込む
                        byte[] buf = new byte[BUFFER_SIZE];
                        for (int size = ds.Read(buf, 0, buf.Length); size > 0; size = ds.Read(buf, 0, buf.Length))
                        {
                            dst.Write(buf, 0, size);
                        }
                    }
                }
            }
        }
    }
}

入力・出力ストリームを引数として共通化することで共通関数を実装しております。

【C#】ファイルの暗号化・複合化を行う。【AES暗号化】

文字列の暗号化・複合化を行うコードの亜種としてファイルを扱う場合を記載します。

Visual Studioの環境構築




using System;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;

namespace TestCode.Utility
{
    public class AesUtil
    {
        /// <summary>
        /// 共有キー
        /// </summary>
        private const string AES_KEY = "-SENJU MURAMASA-";

        /// <summary>
        /// バッファサイズ
        /// </summary>
        private const int BUFFER_SIZE = 1024 * 4;

        /// <summary>
        /// 共有キービットサイズ
        /// </summary>
        private const int KEY_SIZE = 128;

        /// <summary>
        /// 暗号操作のビットサイズ
        /// </summary>
        private const int BLOCK_SIZE = 128;

        /// <summary>
        /// 暗号化
        /// </summary>
        /// <param name="src">入力ファイルパス</param>
        /// <param name="dst">出力ファイルパス</param>
        static public void Encode(string src, string dst)
        {
            // 高度暗号化標準 (AES) 
            using (AesManaged aes = new AesManaged())
            {
                // AESインスタンスのパラメータ設定
                aes.KeySize = KEY_SIZE;
                aes.BlockSize = BLOCK_SIZE;
                aes.Mode = CipherMode.CBC;
                aes.Key = Encoding.UTF8.GetBytes(AES_KEY);

                // 初期化ベクター(IV)の生成
                aes.GenerateIV();

                // 暗号化オブジェクト生成
                ICryptoTransform ct = aes.CreateEncryptor(aes.Key, aes.IV);

                // 出力ファイルストリーム
                using (FileStream outFs = new FileStream(dst, FileMode.Create, FileAccess.Write))
                {
                    // 初期化ベクター(IV)書き込み
                    outFs.Write(aes.IV, 0, aes.IV.Length);

                    // 暗号変換のストリーム(暗号化)
                    using (CryptoStream cs = new CryptoStream(outFs, ct, CryptoStreamMode.Write))
                    {
                        // Deflateアルゴリズムを使用したストリーム(圧縮)
                        using (DeflateStream ds = new DeflateStream(cs, CompressionMode.Compress))
                        {
                            // 入力ファイルストリーム
                            using (FileStream inFs = new FileStream(src, FileMode.Open, FileAccess.Read))
                            {
                                byte[] buf = new byte[BUFFER_SIZE];
                                for (int size = inFs.Read(buf, 0, buf.Length); size > 0; size = inFs.Read(buf, 0, buf.Length))
                                {
                                    // 出力ファイルへ書き込み(圧縮→暗号化→書き込み)
                                    ds.Write(buf, 0, size);
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 複合化
        /// </summary>
        /// <param name="src">入力ファイルパス</param>
        /// <param name="dst">出力ファイルパス</param>
        static public void Decode (string src, string dst)
        {
            // 高度暗号化標準(AES)
            using (AesManaged aes = new AesManaged())
            {
                // AESインスタンスのパラメータ設定
                aes.KeySize = KEY_SIZE;
                aes.BlockSize = BLOCK_SIZE;
                aes.Mode = CipherMode.CBC;
                aes.Key = Encoding.UTF8.GetBytes(AES_KEY);

                // 入力ファイルストリーム
                using (FileStream inFs = new FileStream(src, FileMode.Open, FileAccess.Read))
                {
                    // 初期化ベクター(IV)読込
                    byte[] iv = new byte[aes.IV.Length];
                    inFs.Read(iv, 0, iv.Length);
                    aes.IV = iv;

                    // 複合化オブジェクト生成
                    ICryptoTransform ct = aes.CreateDecryptor(aes.Key, aes.IV);

                    // 暗号変換のストリーム(複合化)
                    using (CryptoStream cs = new CryptoStream(inFs, ct, CryptoStreamMode.Read))
                    {
                        // Deflateアルゴリズムを使用したストリーム(圧縮解除)
                        using (DeflateStream ds = new DeflateStream(cs, CompressionMode.Decompress))
                        {
                            // 出力ファイルストリーム
                            using (FileStream outFs = new FileStream(dst, FileMode.Create, FileAccess.Write))
                            {
                                // 複合化した結果を書き込む
                                byte[] buf = new byte[BUFFER_SIZE];
                                for (int size = ds.Read(buf, 0, buf.Length); size > 0; size = ds.Read(buf, 0, buf.Length))
                                {
                                    outFs.Write(buf, 0, size);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

【C#】文字列の暗号化・複合化を行う。【AES暗号化】

サーバーに配置するテキストファイル内の文字列を暗号化する要件があり、暗号化及び、複合化を行う関数をまとめてみました。

Visual Studioの環境構築



そのまま張り付けるコード


using System;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;

namespace TestCode.Utility
{
    public class AesUtil
    {
        /// <summary>
        /// 共有キー
        /// </summary>
        private const string AES_KEY = "-SENJU MURAMASA-";

        /// <summary>
        /// バッファサイズ
        /// </summary>
        private const int BUFFER_SIZE = 1024 * 4;

        /// <summary>
        /// 共有キービットサイズ
        /// </summary>
        private const int KEY_SIZE = 128;

        /// <summary>
        /// 暗号操作のビットサイズ
        /// </summary>
        private const int BLOCK_SIZE = 128;

        /// <summary>
        /// 暗号化
        /// </summary>
        /// <param name="value">暗号化する文字列</param>
        /// <returns>暗号化した文字列</returns>
        static public string Encode(string value)
        {
            // 高度暗号化標準 (AES) 
            using (AesManaged aes = new AesManaged())
            {
                // AESインスタンスのパラメータ設定
                aes.KeySize = KEY_SIZE;
                aes.BlockSize = BLOCK_SIZE;
                aes.Mode = CipherMode.CBC;
                aes.Key = Encoding.UTF8.GetBytes(AES_KEY);

                // 初期化ベクター(IV)の生成
                aes.GenerateIV();

                // 暗号化オブジェクト生成
                ICryptoTransform ct = aes.CreateEncryptor(aes.Key, aes.IV);

                // 出力ストリーム
                using (MemoryStream outMs = new MemoryStream())
                {
                    // 初期化ベクター(IV)書き込み
                    outMs.Write(aes.IV, 0, aes.IV.Length);

                    // 暗号変換のストリーム(暗号化)
                    using (CryptoStream cs = new CryptoStream(outMs, ct, CryptoStreamMode.Write))
                    {
                        // Deflateアルゴリズムを使用したストリーム(圧縮)
                        using (DeflateStream ds = new DeflateStream(cs, CompressionMode.Compress))
                        {
                            // 文字列を書き込む
                            byte[] buf = Encoding.UTF8.GetBytes(value);
                            ds.Write(buf, 0, buf.Length);
                        }
                    }
                    // BASE64エンコードして返す
                    return Convert.ToBase64String(outMs.ToArray());
                }
            }
        }

        /// <summary>
        /// 複合化
        /// </summary>
        /// <param name="value">暗号化されている文字列</param>
        /// <returns>複合化された文字列</returns>
        static public string Decode(string value)
        {
            // 高度暗号化標準(AES)
            using (AesManaged aes = new AesManaged())
            {
                // AESインスタンスのパラメータ設定
                aes.KeySize = KEY_SIZE;
                aes.BlockSize = BLOCK_SIZE;
                aes.Mode = CipherMode.CBC;
                aes.Key = Encoding.UTF8.GetBytes(AES_KEY);

                // 暗号化文字列ストリーム生成(BASE64でコード)
                using (MemoryStream inMs = new MemoryStream(Convert.FromBase64String(value), false))
                {
                    // 初期化ベクター(IV)読込
                    byte[] iv = new byte[aes.IV.Length];
                    inMs.Read(iv, 0, iv.Length);
                    aes.IV = iv;

                    // 複合化オブジェクト生成
                    ICryptoTransform ct = aes.CreateDecryptor(aes.Key, aes.IV);

                    // 暗号変換のストリーム(複合化)
                    using (CryptoStream cs = new CryptoStream(inMs, ct, CryptoStreamMode.Read))
                    {
                        // Deflateアルゴリズムを使用したストリーム(圧縮解除)
                        using (DeflateStream ds = new DeflateStream(cs, CompressionMode.Decompress))
                        {
                            // 出力ストリーム
                            using (MemoryStream outMs = new MemoryStream())
                            {
                                // 複合化した結果を書き込む
                                byte[] buf = new byte[BUFFER_SIZE];
                                for (int size = ds.Read(buf, 0, buf.Length); size > 0; size = ds.Read(buf, 0, buf.Length))
                                {
                                    outMs.Write(buf, 0, size);
                                }

                                // バイナリデータを文字列変換して返す
                                return Encoding.UTF8.GetString(outMs.ToArray());
                            }
                        }
                    }
                }
            }
        }
    }
}

ごあいさつ

初めまして。

プログラマとして仕事しております。

仕事中で以前に書いた部品系のプログラムコードを再利用しようと思ったときに新規に作ることって多々あるなと思います。

そのため、自分自身にも利用できるブログを開設したいなと思い始めました。

実際のブログ運営は、専業主婦の妻にお任せしてアイデアを出しながらいろいろな情報をメモ書きとして残せたらいいなと思います。

僕自身の趣味的な観点で暴走するかもしれませんが、よろしくお願いいたします。