Dispose() protected method

Dispose the key handles
protected Dispose ( bool disposing ) : void
disposing bool
return void
 private static RSACryptoServiceProvider GenKeys(int keySize)
 {
     var parameters = new CspParameters();
     RSACryptoServiceProvider provider;
     parameters.Flags = CspProviderFlags.NoPrompt | CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey;
     parameters.KeyNumber = (int)KeyNumber.Exchange;
     parameters.KeyContainerName = System.Reflection.Assembly.GetEntryAssembly().FullName;
     try
     {
         //RSAHelper: Attempting to open existing key container
         provider = new RSACryptoServiceProvider(parameters);
         var pa = provider.ExportParameters(false);
         if (pa.Modulus.Length * 8 == keySize) return provider;
         //Found existing key, but not of the correct size
         provider.PersistKeyInCsp = false;
         provider.Clear();
         provider.Dispose();
         GenerateRsaKeys(parameters, keySize, out provider);
     }
     catch
     {
         //No existing Key Container was found in the machine keystore
         GenerateRsaKeys(parameters, keySize, out provider);
     }
     finally
     {
         GC.Collect();
         GC.WaitForPendingFinalizers();
     }
     return provider;
 }
Beispiel #2
0
        /// <summary>
        /// RSA签名,默认SHA256
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <param name="HashbyteSignature"></param>
        /// <param name="EncryptedSignatureData"></param>
        /// <returns></returns>
        public static bool Sign(string privateKey, byte[] HashbyteSignature, out byte[] EncryptedSignatureData)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
            LoadPrivateKey(RSA, privateKey);

            SHA256 sh = new SHA256CryptoServiceProvider();

            EncryptedSignatureData = RSA.SignData(HashbyteSignature, sh);
            sh.Dispose();
            RSA.Dispose();
            return(true);
        }
        public Stream Decrypt(RSAParameters privateKey, string fileName)
        {
            if (!File.Exists(fileName))
            {
                throw new ArgumentException(string.Format("File {0} does not exist", fileName));
            }

            var rsaProvider = new RSACryptoServiceProvider();
            rsaProvider.ImportParameters(privateKey);

            var ms = new MemoryStream();

            using (var fs = new FileStream(fileName, FileMode.Open))
            using (var reader = new StreamReader(fs))
            {
                var keyLength = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);
                var keyString = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);
                var ivLength = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);
                var ivString = ReadUntil(reader, EncryptedXmlWriterTraceListener.Delimiter);

                var key = rsaProvider.Decrypt(Convert.FromBase64String(keyString), false);
                var iv = rsaProvider.Decrypt(Convert.FromBase64String(ivString), false);

                RijndaelManaged rijndaelManaged = new RijndaelManaged();
                rijndaelManaged.Padding = PaddingMode.Zeros;
                rijndaelManaged.IV = iv;
                rijndaelManaged.Key = key;

                fs.Seek(keyLength.Length + int.Parse(keyLength) + ivLength.Length + int.Parse(ivLength) + 4, SeekOrigin.Begin);
                var crypto = new CryptoStream(fs, rijndaelManaged.CreateDecryptor(rijndaelManaged.Key, rijndaelManaged.IV), CryptoStreamMode.Read);
                crypto.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                rijndaelManaged.Dispose();
            }

            rsaProvider.Dispose();
            return ms;
        }
Beispiel #4
0
        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();
            }
        }
Beispiel #5
0
        private string CreateKeyPair()
        {
            ITracer tracer = _traceFactory.GetTracer();
            using (tracer.Step("SSHKeyManager.CreateKey"))
            {
                RSACryptoServiceProvider rsa = null;
                try
                {
                    rsa = new RSACryptoServiceProvider(dwKeySize: KeySize);
                    RSAParameters privateKeyParam = rsa.ExportParameters(includePrivateParameters: true);
                    RSAParameters publicKeyParam = rsa.ExportParameters(includePrivateParameters: false);

                    string privateKey = PEMEncoding.GetString(privateKeyParam);
                    string publicKey = SSHEncoding.GetString(publicKeyParam);

                    FileSystemHelpers.WriteAllText(_id_rsa, privateKey);
                    FileSystemHelpers.WriteAllText(_id_rsaPub, publicKey);

                    FileSystemHelpers.WriteAllText(_config, ConfigContent);
                    EnsureFilePermission();
                    return publicKey;
                }
                finally
                {
                    if (rsa != null)
                    {
                        rsa.PersistKeyInCsp = false;
                        rsa.Dispose();
                    }
                }
            }
        }
        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();
        }
Beispiel #7
0
        public static void TestRSACertificate()
        {
            byte [] bPublicKeyModulus = new byte []
            {
                0xB3, 0x93, 0x18, 0x8B, 0x70, 0xC8, 0x57, 0xFC, 0x0F, 0x75, 0x11, 0xF7, 0x32, 0x2E, 0x6F, 0x91,
                0xD2, 0x76, 0x1F, 0x33, 0x5D, 0xE2, 0x9C, 0x48, 0x84, 0x16, 0xD8, 0x2A, 0x09, 0x1B, 0x42, 0x8D,
                0x31, 0x53, 0x21, 0xCB, 0x44, 0xC7, 0x97, 0x0A, 0x76, 0x18, 0xF5, 0xD6, 0xE8, 0x4B, 0x0C, 0xDD,
                0x5D, 0xBD, 0xA8, 0x47, 0xCD, 0x81, 0x9E, 0xD9, 0x8D, 0xAE, 0x5C, 0x5D, 0xEC, 0x79, 0x99, 0x4B,
                0x1A, 0xD7, 0x69, 0x89, 0x15, 0x0C, 0xA5, 0x51, 0xDC, 0xBF, 0x6A, 0x98, 0x76, 0xE4, 0x17, 0x55,
                0x8E, 0xCE, 0xB7, 0x8A, 0xA0, 0x94, 0xF8, 0xC6, 0x45, 0xA6, 0x89, 0x82, 0x70, 0xA6, 0x40, 0x2A,
                0x03, 0x8A, 0xD5, 0xE7, 0xE9, 0x03, 0x03, 0x63, 0x24, 0x55, 0xB7, 0xA1, 0xAD, 0xF0, 0x7D, 0x02,
                0x63, 0x3C, 0xB5, 0x6B, 0xAD, 0xA5, 0xA1, 0xA2, 0x2A, 0x0A, 0x8F, 0x3D, 0x84, 0x2F, 0x40, 0xF3
            };

            // Taken from openssl on our test certificate
            byte[] bPrivateExponent = new byte[]
            {
                0x42, 0x7e, 0x26, 0x29, 0x83, 0xd2, 0x7b, 0x59, 0xd7, 0x33, 0x67, 0x3a, 0x9c, 0x37, 0x3b,
                0x92, 0xc8, 0x56, 0x7a, 0xc9, 0x1f, 0x6b, 0x88, 0xa9, 0x05, 0x58, 0x1c, 0x24, 0xbc, 0x88,
                0x7e, 0x85, 0x1f, 0x8d, 0x83, 0xc6, 0xeb, 0xa9, 0xe8, 0x10, 0xb4, 0x98, 0x1b, 0x77, 0xbf,
                0x3e, 0x02, 0xfe, 0x78, 0xf6, 0x80, 0x38, 0x4e, 0x2d, 0x3f, 0xef, 0x98, 0x99, 0xc6, 0x93,
                0xf4, 0xbb, 0x35, 0xfa, 0x4d, 0x25, 0x93, 0x3b, 0xfa, 0xf0, 0x35, 0x21, 0x18, 0xe7, 0x16,
                0x5a, 0x21, 0x2a, 0xd1, 0x8e, 0xe4, 0x27, 0xcc, 0xca, 0x84, 0xe5, 0xc6, 0x31, 0x1d, 0x6f,
                0x2f, 0x3c, 0xc6, 0x17, 0x6d, 0x55, 0x2c, 0x1a, 0x95, 0xbe, 0x90, 0x18, 0xf8, 0x44, 0xc0,
                0x8a, 0xdd, 0x1e, 0x11, 0x68, 0x67, 0x42, 0xad, 0x6e, 0xb0, 0x41, 0x68, 0x9d, 0xa8, 0xe6,
                0xf0, 0x81, 0x36, 0xd3, 0x7f, 0x34, 0x16, 0x41
            };

            byte[] bPublicKeyExponent = new byte[] { 0x01, 0x00, 0x01 };

            string strTextToBeEncrypted = "12345";
            string strEncryptedWithPublicKey = "5A D9 BF B9 44 4C C5 F2 0E 9C F5 61 D7 D2 BA B0 54 7A 46 74 BF 3A A3 5E 1D 45 23 9A A0 C8 A0 AF F5 11 16 25 03 3D 77 04 C4 85 80 05 52 FB 83 22 06 63 6C 65 82 A9 75 12 72 E2 82 07 B8 72 EA 30 66 0E 75 6E D2 D4 B6 2F DD B2 61 15 4C D3 53 465B 68 36 F6 C1 3E 90 74 52 07 4E 32 EC 8D 7F A2 F1 71 64 33 F3 2D 99 9A 12 D1 ED ED AB 9D B0 D3 18 A9 B2 E2 99 C0 C7 C3 BA AF EF 51 5C 05 0F 4D";
            string strEncryptedWithPrivateKey= "62 D9 64 6E C2 57 BA 58 92 E0 13 2D EA 36 71 49 83 B6 7D 32 32 EE A6 89 FF 71 8F 60 94 43 6E 85 5D AB FF 52 61 92 A5 EE 8A 9E AE 27 51 3B A3 65 22 C3 EC AB 29 E2 2D EB 29 04 51 D9 6B D4 5F 6C 36 8C 62 80 F7 D3 69 8B A2 51 43 CF B3 9D 03 50A4 FB 93 BB CC 42 5F 20 FF 9B 51 9B 4D 56 30 10 35 14 CE EF E6 52 5F 07 52 AC 98 BB 54 2A 79 0F 08 E8 20 45 6A 77 78 85 0D BF 7B E2 6F F9 43 F8";

            byte[] bTextToBeEncrypted = System.Text.UTF8Encoding.UTF8.GetBytes(strTextToBeEncrypted);
            byte[] bEncryptedWithPublicKey = ByteHelper.ByteFromHexString(strEncryptedWithPublicKey);
            byte[] bEncryptedWithPrivateKey = ByteHelper.ByteFromHexString(strEncryptedWithPrivateKey);

                /// This RSA certificate was generated with OpenSSL.  A file is encrypted with OpenSSL using the private key to make sure we
            /// can decrypt it with the public key
            ///

            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();

            RSAParameters rsaparams = new RSAParameters();
            rsaparams.Modulus = bPublicKeyModulus;
            rsaparams.Exponent = bPublicKeyExponent;
            provider.ImportParameters(rsaparams);

            /// Verified that both of these methods work, they encrypt the string to a form that can be unencrypted (to reproduce "12345")
            /// by using the private key with openssl
            /// Steps taken
            /// Save the debug output hex string produced below as a ascii hex file (384 bytes long)
            /// convert the ascii hex file to a binary file (128 bytes long)
            ///     (I wrote a program called ba.exe to do this)
            /// run openssl against the binary file:
            /// C:\openssl\bin>openssl rsautl -decrypt -in hex2.bin -inkey test_key.pem -out hex2.decrypt
            /// verify that file hex2.decrypt has the ascii contents "12345"  (it did with both outputs below)
            ///
            /// (Note the output is different every time because of PKCS padding applied to make it different every time, this is stripped once it's decrypted)
            ///

            byte[] bEncryptedText1 = provider.Encrypt(bTextToBeEncrypted, false);
            System.Diagnostics.Debug.WriteLine(ByteHelper.HexStringFromByte(bEncryptedText1, true, 16));
            System.Diagnostics.Debug.WriteLine("");

            RSAPKCS1KeyExchangeFormatter formm = new RSAPKCS1KeyExchangeFormatter(provider);
            byte[] bEncryptedText = formm.CreateKeyExchange(bTextToBeEncrypted);
            System.Diagnostics.Debug.WriteLine(ByteHelper.HexStringFromByte(bEncryptedText, true, 16));
            System.Diagnostics.Debug.WriteLine("");
            System.Diagnostics.Debug.WriteLine("");

            provider.Dispose();
        }
Beispiel #8
0
        void HandleHandshakeMessage(TLSHandShakeMessage msg)
        {
            /// Append all our handshake data because we'll need it later for some stupid reason

            if (msg.HandShakeMessageType == HandShakeMessageType.ServerHello)
            {
                ClientTLSState = TLS.ClientTLSState.ReceivedServerHello;
            }
            else if (msg.HandShakeMessageType == HandShakeMessageType.ServerHelloDone)
            {
                if (m_bSendClientCertificate == true) /// got a certificate request from the server, but we don't have any, so send an empty one
                {
                    TLSHandShakeMessage msgclientcert = new TLSHandShakeMessage();
                    msgclientcert.HandShakeMessageType = HandShakeMessageType.Certificate;
                    TLSRecord recordclientcert = new TLSRecord();
                    recordclientcert.MajorVersion = 3;
                    recordclientcert.MinorVersion = 1;
                    recordclientcert.ContentType = TLSContentType.Handshake;
                    recordclientcert.Messages.Add(msgclientcert);

                    SendTLSRecord(recordclientcert, true);
                }

                /// Server has sent the algorithm they want us to use, certificates, parameters,
                /// and any request for certificates from us.  Now let's respond
                /// First generate, encrypt, and send the PreMasterSecret

                byte [] bKey = state.SecurityParameters.PeerCertificate.GetPublicKey();
                byte [] bPreMasterSecret = new byte[48];
                RNGCryptoServiceProvider.GetBytes(bPreMasterSecret);  /// Get some random bytes
                bPreMasterSecret[0] = 0x03; /// first two bytes get set to the version
                bPreMasterSecret[1] = 0x01;

                /// Openssl is showing our modulus as having an extra 00 on the front when using this command
                /// (ignore this, the modulus lower in the output doesn't show the 0)
                /// rsa -in test_key.pem -text

                if (SocketClient.ShowDebug == true)
                {
                    System.Diagnostics.Debug.WriteLine("Client Random: +++++++++++\r\n{0}\r\n++++++++++++", ByteHelper.HexStringFromByte(state.SecurityParameters.ClientRandom, true, 16));
                    System.Diagnostics.Debug.WriteLine("Server Random: +++++++++++\r\n{0}\r\n++++++++++++", ByteHelper.HexStringFromByte(state.SecurityParameters.ServerRandom, true, 16));
                    System.Diagnostics.Debug.WriteLine("PreMasterSecret: +++++++++++\r\n{0}\r\n++++++++++++", ByteHelper.HexStringFromByte(bPreMasterSecret, true, 16));
                }

                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                // Need to use this guys' class to parse the DER encoded ASN.1 described certificate to
                // extract the modulus and e from the certificate - these two are the public key
                RSAParameters rsaparams = Kishore.X509.Parser.X509PublicKeyParser.GetRSAPublicKeyParameters(bKey);
                provider.ImportParameters(rsaparams);

                //System.Diagnostics.Debug.WriteLine("Public key modulus: +++++++++++\r\n{0}\r\n++++++++++++", ByteHelper.HexStringFromByte(rsaparams.Modulus, true, 16));
                //System.Diagnostics.Debug.WriteLine("Public key exponent: +++++++++++\r\n{0}\r\n++++++++++++", ByteHelper.HexStringFromByte(rsaparams.Exponent, true, 16));
                //System.Diagnostics.Debug.WriteLine("Key Exchange Algorithm: {0}, KeySize: {1}", provider.KeyExchangeAlgorithm, provider.KeySize);
                byte[] EncryptedPreMasterSecret = provider.Encrypt(bPreMasterSecret, false);
                provider.Dispose();

                /// Send a Client Key Exchange method with our PreMasterSecret
                ///
                TLSHandShakeMessage msgsend = new TLSHandShakeMessage();
                msgsend.HandShakeMessageType = HandShakeMessageType.ClientKeyExchange;
                msgsend.HandShakeClientKeyExchange.EncryptedPreMasterSecret = EncryptedPreMasterSecret;
                msgsend.HandShakeClientKeyExchange.KeyExchangeAlgorithm = KeyExchangeAlgorithm.rsa;
                msgsend.HandShakeClientKeyExchange.PublicValueEncoding = PublicValueEncoding.explicit_en;
                TLSRecord record = new TLSRecord();
                record.MajorVersion = 3;
                record.MinorVersion = 1;
                record.ContentType = TLSContentType.Handshake;
                record.Messages.Add(msgsend);

                SendTLSRecord(record, true);

                /// Now generate all our keys, etc
                /// Section 8.1
                /// master_secret = PRF(pre_master_secret, "master secret",ClientHello.random + ServerHello.random) [0..47];

                // Combine ClientHello.Random and ServerHello.Random
                ByteBuffer buf = new ByteBuffer();
                buf.AppendData(state.SecurityParameters.ClientRandom);
                buf.AppendData(state.SecurityParameters.ServerRandom);
                byte [] bCSRandom = buf.GetAllSamples();

                // Do it in reverse order for different algorithms
                buf.AppendData(state.SecurityParameters.ServerRandom);
                buf.AppendData(state.SecurityParameters.ClientRandom);
                byte [] bSCRandom = buf.GetAllSamples();

                state.SecurityParameters.MasterSecret = state.PRF(bPreMasterSecret, "master secret", bCSRandom, 48);

                if (SocketClient.ShowDebug == true)
                   System.Diagnostics.Debug.WriteLine("MasterSecret: +++++++++++\r\n{0}\r\n++++++++++++", ByteHelper.HexStringFromByte(state.SecurityParameters.MasterSecret, true, 16));

                /// Verified that we are computing all our keys correctly by using the same input into the Mentalis library
                /// If we coded ours independently and get the same answers, it has to be correct, or we made the same mistakes :)
                state.ComputeKeys(state.SecurityParameters.MasterSecret, bSCRandom);

                /// Now send out a change cipher-spec, followed by a client finished message that is encrypted
                ///
                TLSChangeCipherSpecMessage msgChangeCipherSpec = new TLSChangeCipherSpecMessage();
                msgChangeCipherSpec.CCSProtocolType = CCSProtocolType.Default;
                TLSRecord recordccs = new TLSRecord();
                recordccs.MajorVersion = 3;
                recordccs.MinorVersion = 1;
                recordccs.ContentType = TLSContentType.ChangeCipherSpec;
                recordccs.Messages.Add(msgChangeCipherSpec);
                SendTLSRecord(recordccs, false);

                state.SendEncryptionActive = true;
                state.WriteSequenceNumber = 0; /// reset on changecipherspec

                /// Now send a finished method, encrypted with our generated things
                /// RFC2246 section 7.4.9

                if (SocketClient.ShowDebug == true)
                   System.Diagnostics.Debug.WriteLine("FINAL:  AllHandShakeMessages Length is now {0}", AllHandShakeMessages.Size);

                SHA1Managed sha1 = new SHA1Managed();
                byte[] bAllHandshakeData = AllHandShakeMessages.PeekAllSamples();
                byte[] bmd5OfHandshakeMessages = MD5Core.GetHash(bAllHandshakeData);
                byte[] bsha1OfHandshakeMessages = sha1.ComputeHash(bAllHandshakeData);
                ByteBuffer bSum = new ByteBuffer();
                bSum.AppendData(bmd5OfHandshakeMessages);
                bSum.AppendData(bsha1OfHandshakeMessages);

                byte [] bCombinedHashes = bSum.GetAllSamples();

                /// No use in writing out this debug, only a few of the characters get seen, the rest are dropped
                ///System.Diagnostics.Debug.WriteLine("**** Start all handshake data ****\r\n{0}\r\n**** End all handshake data ****", ByteHelper.HexStringFromByte(bAllHandshakeData, true, 32));
                /// verify_data
                ///     PRF(master_secret, finished_label, MD5(handshake_messages) + SHA-1(handshake_messages)) [0..11];

                TLSHandShakeMessage msgFinished = new TLSHandShakeMessage();
                msgFinished.HandShakeMessageType = HandShakeMessageType.Finished;
                msgFinished.HandShakeFinished.verify_data = state.PRF(state.SecurityParameters.MasterSecret, "client finished", bCombinedHashes, 12);

                TLSRecord recordFinished = new TLSRecord();
                recordFinished.MajorVersion = 3;
                recordFinished.MinorVersion = 1;
                recordFinished.ContentType = TLSContentType.Handshake;
                recordFinished.Messages.Add(msgFinished);

                state.WriteSequenceNumber = 0;
                /// This record must now be encrypted before it can be sent
                SendTLSRecord(recordFinished, true);

                ClientTLSState = ClientTLSState.SentClientFinished;

            }
            else if (msg.HandShakeMessageType == HandShakeMessageType.Finished)
            {
                /// Got the server finished method, let's verify the data
                ///
                SHA1Managed sha1 = new SHA1Managed();
                byte[] bAllHandshakeData = AllHandShakeMessages.GetAllSamples(); // no need to peek here, just get it all and clear it
                byte[] bmd5OfHandshakeMessages = MD5Core.GetHash(bAllHandshakeData);
                byte[] bsha1OfHandshakeMessages = sha1.ComputeHash(bAllHandshakeData);
                ByteBuffer bSum = new ByteBuffer();
                bSum.AppendData(bmd5OfHandshakeMessages);
                bSum.AppendData(bsha1OfHandshakeMessages);

                byte[] bCombinedHashes = bSum.GetAllSamples();

                /// No use in writing out this debug, only a few of the characters get seen, the rest are dropped
                ///System.Diagnostics.Debug.WriteLine("**** Start all handshake data ****\r\n{0}\r\n**** End all handshake data ****", ByteHelper.HexStringFromByte(bAllHandshakeData, true, 32));
                /// verify_data
                ///     PRF(master_secret, finished_label, MD5(handshake_messages) + SHA-1(handshake_messages)) [0..11];

                byte [] bComputedVerify = state.PRF(state.SecurityParameters.MasterSecret, "server finished", bCombinedHashes, 12);
                bool bMatch = ByteHelper.CompareArrays(msg.HandShakeFinished.verify_data, bComputedVerify);
                if (bMatch == false)
                {
                    SendAlert(AlertLevel.fatal, AlertDescription.HandshakeFailure);
                    Client.Disconnect();
                }
                else
                {
                    NegotiationFinished();
                }
            }
            else if (msg.HandShakeMessageType == HandShakeMessageType.CertificateRequest)
            {
                m_bSendClientCertificate = true;
            }

            if (ClientTLSState == TLS.ClientTLSState.ReceivedServerHello)
            {
                /// Gathering information
                ///
                if (msg.HandShakeMessageType == HandShakeMessageType.ServerHello)
                {
                    state.SecurityParameters.Cipher = Cipher.FindCipher(msg.HandShakeServerHello.CipherSuite);
                    state.SecurityParameters.CompressionMethod = CompressionMethod.null0;
                    state.SecurityParameters.ConnectionEnd = ConnectionEnd.client;
                    state.SecurityParameters.ServerRandom = msg.HandShakeServerHello.RandomStruct.Bytes;
                }
                else if (msg.HandShakeMessageType == HandShakeMessageType.Certificate)
                {
                    if (msg.HandShakeCertificateMessage.Certificates.Count > 0)
                        state.SecurityParameters.PeerCertificate = msg.HandShakeCertificateMessage.Certificates[0];
                }
            }
        }
Beispiel #9
0
        // Decrypt a file
        private static Byte[] RSADecrypt(String privateKey, Byte[] dataToEncrypt)
        {
            // Variables
            CspParameters cspParams = null;
            RSACryptoServiceProvider rsaProvider = null;

            byte[] decryptedBytes = null;

            try
            {
                // Select target CSP
                cspParams = new CspParameters();
                cspParams.ProviderType = 1; // PROV_RSA_FULL

                rsaProvider = new RSACryptoServiceProvider(cspParams);

                // Import private/public key pair
                rsaProvider.FromXmlString(privateKey);

                // Decrypt text
                decryptedBytes = rsaProvider.Decrypt(dataToEncrypt, false);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                rsaProvider.Dispose();
            }

            return decryptedBytes;
        }
Beispiel #10
0
        private static Byte[] RSAEncrypt(String publicKey, Byte[] dataToEncrypt)
        {
            CspParameters cspParams = null;
            RSACryptoServiceProvider rsaProvider = null;

            Byte[] encryptedBytes = null;

            try
            {
                // Select target CSP /
                cspParams = new CspParameters();
                cspParams.ProviderType = 1; // PROV_RSA_FULL
                rsaProvider = new RSACryptoServiceProvider(cspParams);

                // Import public key
                rsaProvider.FromXmlString(publicKey);

                encryptedBytes = rsaProvider.Encrypt(dataToEncrypt, false);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                rsaProvider.Dispose();
            }

            return encryptedBytes;
        }
Beispiel #11
0
        private string CreateKey()
        {
            RSACryptoServiceProvider rsa = null;
            try
            {
                rsa = new RSACryptoServiceProvider(dwKeySize: KeySize);
                RSAParameters privateKeyParam = rsa.ExportParameters(includePrivateParameters: true);
                RSAParameters publicKeyParam = rsa.ExportParameters(includePrivateParameters: false);

                string privateKey = PEMEncoding.GetString(privateKeyParam);
                string publicKey = SSHEncoding.GetString(publicKeyParam);

                _fileSystem.File.WriteAllText(_id_rsa, privateKey);
                _fileSystem.File.WriteAllText(_id_rsaPub, publicKey);

                _fileSystem.File.WriteAllText(_config, ConfigContent);

                return publicKey;
            }
            finally
            {
                if (rsa != null)
                {
                    rsa.PersistKeyInCsp = false;
                    rsa.Dispose();
                }
            }
        }
Beispiel #12
0
 private void расшифроватьСообщение(object sender, EventArgs e)
 {
     OpenFileDialog диалоговоеОкноОткрытияФайла = new OpenFileDialog();
     диалоговоеОкноОткрытияФайла.Filter = фильтрЗакрытогоКлюча;
     диалоговоеОкноОткрытияФайла.FilterIndex = 1;
     диалоговоеОкноОткрытияФайла.Title = "Выберите файл закрытого ключа.";
     диалоговоеОкноОткрытияФайла.Multiselect = false;
     диалоговоеОкноОткрытияФайла.RestoreDirectory = true;
     if (диалоговоеОкноОткрытияФайла.ShowDialog() == DialogResult.OK)
     {
         try
         {
             StreamReader потокЧитающийИзФайла = new StreamReader(диалоговоеОкноОткрытияФайла.FileName);
             string ключ = потокЧитающийИзФайла.ReadToEnd();
             RSACryptoServiceProvider RSACSP = new RSACryptoServiceProvider();
             RSACSP.FromXmlString(ключ);
             int началоСообщения = полученноеСообщение.Body.IndexOf("<MSG>") + 5;
             int конецСообщения = полученноеСообщение.Body.IndexOf("</MSG>") - 5;
             string телоСообщения = полученноеСообщение.Body.Substring(началоСообщения, конецСообщения - началоСообщения);
             byte[] массивБайтов =  HEXStringToByte(телоСообщения);
             string временнаяСтрока = string.Empty;
             int количествоБлоков = массивБайтов.Length / 128;
             for (int i = 0; i < количествоБлоков; i++)
             {
                 byte[] веременныйМассив = массивБайтов.Skip(128 * i).ToArray().Take(128).ToArray();
                 временнаяСтрока += ByteToHEXString(RSACSP.Decrypt(веременныйМассив, true));
             }
             телоСообщения = Encoding.UTF32.GetString(HEXStringToByte(временнаяСтрока));
             полеОтображенияСообщения.Clear();
             полеОтображенияСообщения.AppendText("От: " + полученноеСообщение.From.Address);
             полеОтображенияСообщения.AppendText("\nТема: " + полученноеСообщение.Subject);
             полеОтображенияСообщения.AppendText("\nСообщение: " +телоСообщения+полученноеСообщение.Body.Substring(конецСообщения+6));
             потокЧитающийИзФайла.Close();
             RSACSP.Dispose();
         }
         catch (Exception exp)
         {
             показатьСообщениеОбОшибке(exp);
         }
     }
 }