2007年6月16日土曜日

Rijndael(ラインダール)暗号の実装

なんか十行でズバリの暗号がトリプルDESだったので



http://www.microsoft.com/japan/msdn/thisweek/300x10/phase2/encrypt/cs.aspx



ラインダールは自分で実装するのかよ、みたいな感じでグーグルしても適当なサンプルが見つからない....
結局一番詳しかったのはRijndaelクラスの説明をしてるヘルプファイルのサンプルだった....
灯台元暗し(泣



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;



using System.Security.Cryptography;
using System.IO;



namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();



            textBox1.Text = "Here is some data to encrypt.";
        }



        private void button1_Click(object sender, EventArgs e)
        {
            String errmsg = "";



            try
            {



                // Create a new Rijndael object to generate a key
                // and initialization vector (IV).
                Rijndael RijndaelAlg = Rijndael.Create();



                // Create a string to encrypt.
                //string sData = "Here is some data to encrypt.";
                string sData = textBox1.Text;
                string FileName = "CText.txt";



                // Encrypt text to a file using the file name, key, and IV.
                // 注意!!長い文章を暗号化した後に短い文章を暗号化すると長い文章の残骸が残って復号不可能になる
                EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV,errmsg);



                // Decrypt the text from a file using the file name, key, and IV.
                string Final = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV, errmsg);



                // Display the decrypted string to the console.
                label1.Text = Final;
                //Console.WriteLine(Final);
            }
            catch (Exception ex)
            {
                label1.Text = ex.Message;
                //Console.WriteLine(ex.Message);
            }
            MessageBox.Show("終了 " + errmsg);
        }



        /// <summary>
        /// テキストを暗号化してファイルに格納する
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="FileName"></param>
        /// <param name="Key"></param>
        /// <param name="IV"></param>
        /// <param name="errmsg"></param>
        public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV, String errmsg)
        {
            try
            {
                // Create or open the specified file.
                FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);



                // Create a new Rijndael object.
                Rijndael RijndaelAlg = Rijndael.Create();



                // Create a CryptoStream using the FileStream
                // and the passed key and initialization vector (IV).
                CryptoStream cStream = new CryptoStream(fStream, RijndaelAlg.CreateEncryptor(Key, IV), CryptoStreamMode.Write);



                // Create a StreamWriter using the CryptoStream.
                StreamWriter sWriter = new StreamWriter(cStream);



                try
                {
                    // Write the data to the stream
                    // to encrypt it.
                    sWriter.WriteLine(Data);
                }
                catch (Exception e)
                {
                    errmsg = "An error occurred: " + e.Message;
                }
                finally
                {
                    // Close the streams and
                    // close the file.
                    sWriter.Close();
                    cStream.Close();
                    fStream.Close();
                }
            }
            catch (CryptographicException e)
            {
                errmsg = "A Cryptographic error occurred: " + e.Message;
            }
            catch (UnauthorizedAccessException e)
            {
                errmsg = "A file error occurred: " + e.Message;
            }



        }



        /// <summary>
        /// ファイル内テキストを復号化して文字列で返す
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="Key"></param>
        /// <param name="IV"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV, String errmsg)
        {
            try
            {
                // Create or open the specified file.
                FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);



                // Create a new Rijndael object.
                Rijndael RijndaelAlg = Rijndael.Create();



                // Create a CryptoStream using the FileStream
                // and the passed key and initialization vector (IV).
                CryptoStream cStream = new CryptoStream(fStream, RijndaelAlg.CreateDecryptor(Key, IV), CryptoStreamMode.Read);



                // Create a StreamReader using the CryptoStream.
                StreamReader sReader = new StreamReader(cStream);



                string val = null;



                try
                {
                    // Read the data from the stream
                    // to decrypt it.
                    val = sReader.ReadLine();
                }
                catch (Exception e)
                {
                    errmsg = "An error occurred: " + e.Message;
                }
                finally
                {



                    // Close the streams and
                    // close the file.
                    sReader.Close();
                    cStream.Close();
                    fStream.Close();
                }



                // Return the string.
                return val;
            }
            catch (CryptographicException e)
            {
                errmsg = "A Cryptographic error occurred: " + e.Message;
                return null;
            }
            catch (UnauthorizedAccessException e)
            {
                errmsg = "A file error occurred: " + e.Message;
                return null;
            }
        }
    }
}



0 件のコメント:

コメントを投稿