Dispose() 보호된 메소드

protected Dispose ( bool disposing ) : void
disposing bool
리턴 void
예제 #1
0
파일: Client.cs 프로젝트: jodufra/aulas_si
        static void Main(string[] args)
        {
            Console.WriteLine("CLIENT\n");
            TcpClient tcpc = null;
            NetworkStream stream = null;
            TripleDESCryptoServiceProvider crypt3des = null;
            SymmetricsSI symmetrics = null;
            RSACryptoServiceProvider rsaClient = null;
            RSACryptoServiceProvider rsaServer = null;

            try
            {
                tcpc = new TcpClient();
                tcpc.Connect("", 9999);
                stream = tcpc.GetStream();

                ProtocolSI protocol = new ProtocolSI();
                byte[] packet;

                crypt3des = new TripleDESCryptoServiceProvider();
                symmetrics = new SymmetricsSI(crypt3des);
                rsaClient = new RSACryptoServiceProvider();
                string privateAndPublicKeyFilename = "clientpvpbkey.txt";
                rsaServer = new RSACryptoServiceProvider();
                if (File.Exists(privateAndPublicKeyFilename)) rsaClient.FromXmlString(File.ReadAllText(privateAndPublicKeyFilename));
                else File.WriteAllText(privateAndPublicKeyFilename, rsaClient.ToXmlString(true));

                var ack = protocol.Make(ProtocolSICmdType.ACK);

                // Send key
                Console.WriteLine("sending for client public key");
                packet = protocol.Make(ProtocolSICmdType.PUBLIC_KEY, rsaClient.ToXmlString(false));
                stream.Write(packet, 0, packet.Length);
                Console.WriteLine("ok");

                Console.WriteLine("waiting for server public key");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                rsaServer.FromXmlString(protocol.GetStringFromData());
                Console.WriteLine("ok");
                Console.WriteLine("SERVER PUBLIC KEY: " + rsaServer.ToXmlString(false));

                Console.WriteLine("waiting for 3des key");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.Key = rsaServer.Decrypt(protocol.GetData(), false);
                Console.WriteLine("ok");
                Console.WriteLine("3DES KEY: " + crypt3des.Key.ToString());

                Console.WriteLine("waiting for 3des iv");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.IV = rsaServer.Decrypt(protocol.GetData(), false);
                Console.WriteLine("ok");
                Console.WriteLine("3DES IV: " + crypt3des.IV.ToString());

                Console.WriteLine("waiting for 3des padding");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.Padding = (PaddingMode)BitConverter.ToInt32(rsaServer.Decrypt(protocol.GetData(), false), 0);
                Console.WriteLine("ok");
                Console.WriteLine("3DES PADDING: " + crypt3des.Padding.ToString());

                Console.WriteLine("waiting for 3des mode");
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                stream.Write(ack, 0, ack.Length);
                crypt3des.Mode = (CipherMode)BitConverter.ToInt32(rsaServer.Decrypt(protocol.GetData(), false), 0);
                Console.WriteLine("ok");
                Console.WriteLine("3DES MODE: " + crypt3des.Mode.ToString());

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                Console.WriteLine("disconnected");
                if (stream != null) stream.Dispose();
                if (tcpc != null) tcpc.Close();
                if (crypt3des != null) crypt3des.Dispose();
                if (symmetrics != null) crypt3des.Dispose();
                if (rsaClient != null) rsaClient.Dispose();
                if (rsaServer != null) rsaServer.Dispose();
            }
        }
예제 #2
0
        /// <summary>
        /// Encrypts/decrypts a byte array
        /// </summary>
        /// <param name="buffer">Bytes to crypt</param>
        /// <param name="key">"Password" for encryption</param>
        /// <param name="iv">"Salt" for encryption. A starting point for encryption.</param>
        /// <param name="encrypt">Do you wish to encrypt or decrypt?</param>
        /// <param name="algorithm">Encryption algorithm. AES/DES/TripleDES</param>
        /// <returns></returns>
        public static byte[] Crypt(byte[] buffer, byte[] key, byte[] iv, bool encrypt = true, string algorithm = "aes")
        {

            AesCryptoServiceProvider aes = null;
            DESCryptoServiceProvider des = null;
            TripleDESCryptoServiceProvider tripsDes = null;

            ICryptoTransform cryptor;

            switch (algorithm.ToLower())
            {

                case "aes":
                    aes = new AesCryptoServiceProvider();
                    aes.Key = key;
                    aes.IV = iv;
                    //aes.Padding = PaddingMode.None;

                    if (encrypt) cryptor = aes.CreateEncryptor();
                    else cryptor = aes.CreateDecryptor();

                    break;

                case "des":
                    des = new DESCryptoServiceProvider();
                    des.Key = key;
                    des.IV = iv;
                    //des.Padding = PaddingMode.None;

                    if (encrypt) cryptor = des.CreateEncryptor();
                    else cryptor = des.CreateDecryptor();

                    break;

                case "tripledes":
                    tripsDes = new TripleDESCryptoServiceProvider();
                    tripsDes.Key = key;
                    tripsDes.IV = iv;
                    //tripsDes.Padding = PaddingMode.None;


                    if (encrypt) cryptor = tripsDes.CreateEncryptor();
                    else cryptor = tripsDes.CreateDecryptor();

                    break;

                default:
                    throw new ArgumentException(algorithm + " is not an implemented encryption algorithm. Use AES/DES/TripleDES.");

            }
            try
            {

                return cryptor.TransformFinalBlock(buffer, 0, buffer.Length);

            }
            catch (CryptographicException)
            {
                throw new ArgumentException("Ensure you have the right key/IV.");
            }
            finally
            {

                                        cryptor.Dispose();
                if (aes != null)        aes.Dispose();
                if (des != null)        des.Dispose();
                if (tripsDes != null)   tripsDes.Dispose();

            }

        }
예제 #3
0
        static void Main(string[] args)
        {
            const int n = 100 * 1000;
            var sw = new Stopwatch();
            Random r = new Random();
            var data = new byte[1024];
            var key8B = new byte[8];
            var key16B = new byte[16];
            var key24B = new byte[24];
            var key32B = new byte[32];
            r.NextBytes(data);
            r.NextBytes(key8B);
            r.NextBytes(key16B);
            r.NextBytes(key24B);
            r.NextBytes(key32B);
            Action<string> outputToConsole = (s) =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(s);
            };

            // AES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("AES");
            var aes = new AesCryptoServiceProvider();
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = key16B;
            Action doAes = () => EncryptDecryptAndDispose(aes.CreateEncryptor(), aes.CreateDecryptor(), data);
            doAes.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            aes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("DES");
            var des = new DESCryptoServiceProvider();
            des.IV = key8B;
            des.Key = key8B;
            Action doDes = () => EncryptDecryptAndDispose(des.CreateEncryptor(), des.CreateDecryptor(), data);
            doDes.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            des.Dispose();

            // RC2
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RC2");
            var rc2 = new RC2CryptoServiceProvider();
            rc2.IV = key8B;
            rc2.Key = key8B;
            Action doRc2 = () => EncryptDecryptAndDispose(rc2.CreateEncryptor(), rc2.CreateDecryptor(), data);
            doRc2.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            rc2.Dispose();

            // Rijndael
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("Rijndael");
            var rijndael = new RijndaelManaged();
            rijndael.IV = key16B;
            rijndael.Key = key16B;
            Action doRijndael = () => EncryptDecryptAndDispose(rijndael.CreateEncryptor(), rijndael.CreateDecryptor(), data);
            doRijndael.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            rijndael.Dispose();

            // 3DES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("3DES");
            var tripleDes = new TripleDESCryptoServiceProvider();
            tripleDes.IV = key8B;
            tripleDes.Key = key24B;
            Action do3des = () => EncryptDecryptAndDispose(tripleDes.CreateEncryptor(), tripleDes.CreateDecryptor(), data);
            do3des.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            tripleDes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RSA");
            RSAParameters param = new RSAParameters();
            param.Exponent = new byte[] {0, 1, 0};
            var store = new X509Store(StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            X509Certificate cert = null;
            foreach (X509Certificate cer in store.Certificates)
            {
                if (cer != null)
                {
                    cert = cer;
                    break;
                }
            }
            param.Modulus = cert.GetPublicKey();

            var rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(param);

            Action doRsa = () =>
                {

                    var encryptedData = rsa.Encrypt(key32B, true);
                    //var decryptedData = rsa.Decrypt(encryptedData, true);
                };
            doRsa.Repeat(n)
                .OutputPerformance(sw, outputToConsole)();
            rsa.Dispose();

            Console.Read();
        }
예제 #4
0
        /// <summary>
        /// Create a new SymmCipher object with a random key based on the alg and mode supplied.
        /// </summary>
        /// <param name="algId"></param>
        /// <param name="numBits"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static SymmCipher Create(SymDefObject symDef = null, byte[] keyData = null, byte[] iv = null)
        {
            if (symDef == null)
            {
                symDef = new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb);
            }

#if TSS_USE_BCRYPT
            BCryptAlgorithm alg = null;

            switch (symDef.Algorithm)
            {
                case TpmAlgId.Aes:
                    alg = new BCryptAlgorithm(Native.BCRYPT_AES_ALGORITHM);
                    break;
                case TpmAlgId.Tdes:
                    alg = new BCryptAlgorithm(Native.BCRYPT_3DES_ALGORITHM);
                    break;
                default:
                    Globs.Throw<ArgumentException>("Unsupported symmetric algorithm " + symDef.Algorithm);
                    break;
            }

            if (keyData == null)
            {
                keyData = Globs.GetRandomBytes(symDef.KeyBits / 8);
            }
            var key = alg.GenerateSymKey(symDef, keyData, GetBlockSize(symDef));
            //key = BCryptInterface.ExportSymKey(keyHandle);
            //keyHandle = alg.LoadSymKey(key, symDef, GetBlockSize(symDef));
            alg.Close();
            return key == null ? null : new SymmCipher(key, keyData, iv);
#else
            SymmetricAlgorithm alg = null; // = new RijndaelManaged();
            bool limitedSupport = false;
            // DES and __3DES are not supported in TPM 2.0 rev. 0.96 to 1.30
            switch (symDef.Algorithm) {
                case TpmAlgId.Aes:
                    alg = new RijndaelManaged();
                    break;
                case TpmAlgId.Tdes:
                    alg = new TripleDESCryptoServiceProvider();
                    limitedSupport = true;
                    break;
                default:
                    Globs.Throw<ArgumentException>("Unsupported symmetric algorithm " + symDef.Algorithm);
                    break;
            }

            int blockSize = GetBlockSize(symDef);
            alg.KeySize = symDef.KeyBits;
            alg.BlockSize = blockSize * 8;
            alg.Padding = PaddingMode.None;
            alg.Mode = GetCipherMode(symDef.Mode);

            // REVISIT: Get this right for other modes
            if (symDef.Algorithm == TpmAlgId.Tdes && symDef.Mode == TpmAlgId.Cfb)
            {
                alg.FeedbackSize = 8;
            }
            else
            {
                alg.FeedbackSize = alg.BlockSize;
            }

            if (keyData == null)
            {
                // Generate random key
                alg.IV = Globs.GetZeroBytes(blockSize);
                try
                {
                    alg.GenerateKey();
                }
                catch (Exception)
                {
                    alg.Dispose();
                    throw;
                }
            }
            else
            {
                // Use supplied key bits
                alg.Key = keyData;
                if (iv == null)
                {
                    iv = Globs.GetZeroBytes(blockSize);
                }
                else if (iv.Length != blockSize)
                {
                    Array.Resize(ref iv, blockSize);
                }
                alg.IV = iv;
            }

            var symCipher = new SymmCipher(alg);
            symCipher.LimitedSupport = limitedSupport;
            return symCipher;
#endif
        }
예제 #5
0
파일: Client.cs 프로젝트: jodufra/aulas_si
        static void Main(string[] args)
        {
            TcpClient tcpc = null;
            NetworkStream stream = null;
            TripleDESCryptoServiceProvider crypto = null;
            SymmetricsSI symmetrics = null;

            try
            {
                Console.Write("A ligar ao servidor... ");
                tcpc = new TcpClient();
                tcpc.Connect("", 9999);
                Console.WriteLine("ok");
                stream = tcpc.GetStream();

                ProtocolSI protocol = new ProtocolSI();
                byte[] packet;

                crypto = new TripleDESCryptoServiceProvider();
                symmetrics = new SymmetricsSI(crypto);

                // Send key

                packet = protocol.Make(ProtocolSICmdType.PADDING, (int)crypto.Padding);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.IV, crypto.IV);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.MODE, (int)crypto.Mode);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.SECRET_KEY, crypto.Key);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                packet = protocol.Make(ProtocolSICmdType.EOF);
                stream.Write(packet, 0, packet.Length);
                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);

                var message = symmetrics.Encrypt(Encoding.UTF8.GetBytes("HelloWorld"));
                packet = protocol.Make(ProtocolSICmdType.SYM_CIPHER_DATA, message);
                stream.Write(packet, 0, packet.Length);

                stream.Read(protocol.Buffer, 0, protocol.Buffer.Length);
                if (protocol.GetCmdType() != ProtocolSICmdType.ACK)
                    throw new Exception("Server could not decrypt");

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                Console.WriteLine("disconnected");
                if (stream != null) stream.Dispose();
                if (tcpc != null) tcpc.Close();
                if (crypto != null) crypto.Dispose();
                if (symmetrics != null) crypto.Dispose();
            }
        }