C鏣暗号解読クラスの実例プログラム

18636 ワード

二年前に書いたものを整理して送ります。以前、会社はWebServiceをしなければなりませんでした。そして、WebServiceのSoappHeaderを暗号化しています。このクラスを使うには鍵の管理が必要です。データの安全性を保証するためには、データを暗号化しがちですが、暗号化の欠点の一つは、プログラムの動作効率に影響を与えます。だから、ユーザの登録情報(ユーザ名、パスワード)だけを暗号化するという考えです。データは平文で伝送され、ユーザ情報の検証が通らなかった場合、データ転送は行われません。実際には、ネットワーク通信において、秘密鍵を使用する方法は完璧ではありません。もしハッカーが鍵で暗号化されたものを捉え、ユーザーが情報を検証し、その後、シミュレーション要求を行い、WebServiceを提供するサーバに要求を送ることができますか?それとも要求データを得ることができますか?だから、私はまたIPあるいはドメインのバインディングの方式を使いました!結局、WebServiceは最終ユーザーに直接提供したのではないです。このような手段を加えると、不良な意図者が不正にWebServiceのサービスを獲得したいと思っても、もうちょっと苦労しましょう。もう一つの安全提案があります。定期的に鍵を交換します。この例では対称暗号を使っています。暗号化者と暗号解読者の鍵は一致しています。定期的に鍵を交換すると、安全性が向上します。みんなはもっと良い方法があって、あるいは提案があって、伝言を残して討論することができます!共に向上します!
コードは以下の通りです

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

namespace SEDO
{
    /// <summary>
    /// SEDO 。
    /// SEDO 4 (Des,Rc2,Rijndael,TripleDes)
    ///
    /// :
    /// 1:TripleDes Rijndael / 16 24 byte Key
    /// 2:Rijndael 16 IV
    /// 3:Des Rc2 8 Byte Key IV
    /// 4: / / ,
    /// 5: IV
    /// : 2010-10-30 [email protected]
    /// </summary>

    //
    public enum EncryptionAlgorithm { Des = 1, Rc2, Rijndael, TripleDes };

    //
    internal class EncryptTransformer
    {
        private EncryptionAlgorithm algorithmID;
        private byte[] initVec;
        private byte[] encKey;

        internal EncryptTransformer(EncryptionAlgorithm algId)
        {
            //Save the algorithm being used.
            algorithmID = algId;
        }

        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            // Key IV ,
            // Key IV
            switch (algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    {
                        DES des = new DESCryptoServiceProvider();
                        des.Mode = CipherMode.CBC;

                        // See if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = des.Key;
                        }
                        else
                        {
                            des.Key = bytesKey;
                            encKey = des.Key;
                        }
                        // See if the client provided an initialization vector
                        if (null == initVec)
                        { // Have the algorithm create one
                            initVec = des.IV;
                        }
                        else
                        { //No, give it to the algorithm
                            des.IV = initVec;
                        }
                        return des.CreateEncryptor();
                    }
                case EncryptionAlgorithm.TripleDes:
                    {
                        TripleDES des3 = new TripleDESCryptoServiceProvider();
                        des3.Mode = CipherMode.CBC;
                        // See if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = des3.Key;
                        }
                        else
                        {
                            des3.Key = bytesKey;
                            encKey = des3.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = des3.IV;
                        }
                        else
                        { //No, give it to the alg.
                            des3.IV = initVec;
                        }
                        return des3.CreateEncryptor();
                    }
                case EncryptionAlgorithm.Rc2:
                    {
                        RC2 rc2 = new RC2CryptoServiceProvider();
                        rc2.Mode = CipherMode.CBC;
                        // Test to see if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = rc2.Key;
                        }
                        else
                        {
                            rc2.Key = bytesKey;
                            encKey = rc2.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = rc2.IV;
                        }
                        else
                        { //No, give it to the alg.
                            rc2.IV = initVec;
                        }
                        return rc2.CreateEncryptor();
                    }
                case EncryptionAlgorithm.Rijndael:
                    {
                        Rijndael rijndael = new RijndaelManaged();
                        rijndael.Mode = CipherMode.CBC;
                        // Test to see if a key was provided
                        if (null == bytesKey)
                        {
                            encKey = rijndael.Key;
                        }
                        else
                        {
                            rijndael.Key = bytesKey;
                            encKey = rijndael.Key;
                        }
                        // See if the client provided an IV
                        if (null == initVec)
                        { //Yes, have the alg create one
                            initVec = rijndael.IV;
                        }
                        else
                        { //No, give it to the alg.
                            rijndael.IV = initVec;
                        }
                        return rijndael.CreateEncryptor();
                    }
                default:
                    {
                        throw new CryptographicException("Algorithm ID '" +
                        algorithmID +
                        "' not supported.");
                    }
            }
        }

        //
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }
        //
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

    }

    //
    internal class DecryptTransformer
    {
        private EncryptionAlgorithm algorithmID;
        private byte[] initVec;
        private byte[] encKey;

        internal DecryptTransformer(EncryptionAlgorithm deCryptId)
        {
            algorithmID = deCryptId;
        }

        //
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

        //
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

        internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey)
        {
            // Key IV ,
            // Key IV
            switch (algorithmID)
            {
                case EncryptionAlgorithm.Des:
                    {
                        DES des = new DESCryptoServiceProvider();
                        des.Mode = CipherMode.CBC;
                        des.Key = bytesKey;
                        des.IV = initVec;
                        return des.CreateDecryptor();
                    }
                case EncryptionAlgorithm.TripleDes:
                    {
                        TripleDES des3 = new TripleDESCryptoServiceProvider();
                        des3.Mode = CipherMode.CBC;
                        return des3.CreateDecryptor(bytesKey, initVec);
                    }
                case EncryptionAlgorithm.Rc2:
                    {
                        RC2 rc2 = new RC2CryptoServiceProvider();
                        rc2.Mode = CipherMode.CBC;
                        return rc2.CreateDecryptor(bytesKey, initVec);
                    }
                case EncryptionAlgorithm.Rijndael:
                    {
                        Rijndael rijndael = new RijndaelManaged();
                        rijndael.Mode = CipherMode.CBC;
                        return rijndael.CreateDecryptor(bytesKey, initVec);
                    }
                default:
                    {
                        throw new CryptographicException("Algorithm ID '" +
                        algorithmID +
                        "' not supported.");
                    }
            }
        } //end GetCryptoServiceProvider

    }

    //
    public class Encryptor
    {
        private EncryptTransformer transformer;
        private byte[] initVec;
        private byte[] encKey;

        public Encryptor(EncryptionAlgorithm algId)
        {
            transformer = new EncryptTransformer(algId);
        }

        public byte[] Encrypt(byte[] bytesData, byte[] bytesKey, byte[] bytesIV)
        {
            // .
            MemoryStream memStreamEncryptedData = new MemoryStream();

            transformer.IV = bytesIV;
            transformer.Key = bytesKey;

            ICryptoTransform transform =
                transformer.GetCryptoServiceProvider(bytesKey);
            CryptoStream encStream =
                new CryptoStream(memStreamEncryptedData,
                    transform, CryptoStreamMode.Write);

            try
            {
                //
                encStream.Write(bytesData, 0, bytesData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(" !"+
                    " :
" + ex.Message);
            }

            // Key IV
            encKey = transformer.Key;
            initVec = transformer.IV;

            encStream.FlushFinalBlock();
            encStream.Close();

            //Send the data back.
            return memStreamEncryptedData.ToArray();
        }

        public byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

        public byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

    }

 
    //
    public class Decryptor
    {
        private DecryptTransformer transformer;
        private byte[] initVec;
        private byte[] encKey;

        public Decryptor(EncryptionAlgorithm algId)
        {
            transformer = new DecryptTransformer(algId);
        }

        public byte[] Decrypt(byte[] bytesData,
            byte[] bytesKey, byte[] bytesIV)
        {
            // .
            MemoryStream memStreamDecryptedData =
                new MemoryStream();

            //Pass in the initialization vector.
            transformer.IV = bytesIV;
            transformer.Key = bytesKey;

            ICryptoTransform transform =
                transformer.GetCryptoServiceProvider(bytesKey);
            CryptoStream decStream =
                new CryptoStream(memStreamDecryptedData,
                    transform, CryptoStreamMode.Write);

            try
            {
                decStream.Write(bytesData, 0, bytesData.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(" !"+
                    " :
" + ex.Message);
            }
            decStream.FlushFinalBlock();
            decStream.Close();
            // .
            return memStreamDecryptedData.ToArray();
        }

        public byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }

        public byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

    }

    // : /
    public class SecurityFile
    {
        private DecryptTransformer Dec_Transformer; //
        private EncryptTransformer Enc_Transformer; //
        private byte[] initVec;
        private byte[] encKey;

        public SecurityFile(EncryptionAlgorithm algId)
        {
            Dec_Transformer = new DecryptTransformer(algId);
            Enc_Transformer = new EncryptTransformer(algId);
        }

        //
        internal byte[] IV
        {
            get { return initVec; }
            set { initVec = value; }
        }
        //
        internal byte[] Key
        {
            get { return encKey; }
            set { encKey = value; }
        }

        // :
        public void EncryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, FileMode.Open,
                        FileAccess.Read);
                FileStream fout = new FileStream(outFileName,
                    FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

                //Create variables to help with read and write.
                //This is intermediate storage for the encryption.
                byte[] bin = new byte[100];
                //This is the total number of bytes written.
                long rdlen = 0;
                //This is the total length of the input file.
                long totlen = fin.Length;
                //This is the number of bytes to be written at a time.
                int len;

                Enc_Transformer.IV = bytesIV;
                Enc_Transformer.Key = bytesKey;

                ICryptoTransform transform =
                    Enc_Transformer.GetCryptoServiceProvider(bytesKey);
                CryptoStream encStream =
                    new CryptoStream(fout, transform, CryptoStreamMode.Write);

                //Read from the input file, then encrypt and write to the output file.
                while (rdlen < totlen)
                {
                    len = fin.Read(bin, 0, 100);
                    encStream.Write(bin, 0, len);
                    rdlen = rdlen + len;
                }

                encStream.Close();
                fout.Close();
                fin.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(" !"+
                    " :
" + ex.Message);
            }
        }

        // :
        public void DecryptFile(string inFileName,
            string outFileName, byte[] bytesKey, byte[] bytesIV)
        {
            try
            {
                FileStream fin =
                    new FileStream(inFileName, FileMode.Open,
                        FileAccess.Read);
                FileStream fout =
                    new FileStream(outFileName,
                        FileMode.OpenOrCreate, FileAccess.Write);
                fout.SetLength(0);

                //Create variables to help with read and write.
                //This is intermediate storage for the encryption.
                byte[] bin = new byte[100];
                //This is the total number of bytes written.
                long rdlen = 0;
                //This is the total length of the input file.
                long totlen = fin.Length;
                //This is the number of bytes to be written at a time.
                int len;

                Dec_Transformer.IV = bytesIV;
                Dec_Transformer.Key = bytesKey;

                ICryptoTransform transform =
                    Dec_Transformer.GetCryptoServiceProvider(bytesKey);
                CryptoStream encStream =
                    new CryptoStream(fout, transform, CryptoStreamMode.Write);

                //Read from the input file, then encrypt and
                //write to the output file.
                while (rdlen < totlen)
                {
                    len = fin.Read(bin, 0, 100);
                    encStream.Write(bin, 0, len);
                    rdlen = rdlen + len;
                }
                encStream.Close();
                fout.Close();
                fin.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(" "+
                    " ! :
" + ex.Message);
            }
        }
    }
}