private void encryptMenuItem_Click(object sender, EventArgs e)
 {
     if (inputTextBox.Text.Length != 0)
     {
         openFileDialog.FileName = "";
         openFileDialog.Title    = "Open Public Key File";
         openFileDialog.Filter   = "Public Key Document( *.pke )|*.pke";
         string fileString = null;
         if (openFileDialog.ShowDialog() == DialogResult.OK)
         {
             if (File.Exists(openFileDialog.FileName))
             {
                 StreamReader streamReader = new StreamReader(openFileDialog.FileName, true);
                 fileString = streamReader.ReadToEnd();
                 streamReader.Close();
                 if (fileString.Length >= inputTextBox.MaxLength)
                 {
                     MessageBox.Show("ERROR: \nThe file you are trying to open is too big for the text editor to display properly.\nPlease open a smaller document!\nOperation Aborted!");
                 }
             }
         }
         if (fileString != null)
         {
             FinishedProcessDelegate finishedProcessDelegate = new FinishedProcessDelegate(FinishedProcess);
             UpdateTextDelegate      updateTextDelegate      = new UpdateTextDelegate(UpdateText);
             string bitStrengthString = fileString.Substring(0, fileString.IndexOf("</BitStrength>") + 14);
             fileString = fileString.Replace(bitStrengthString, "");
             int   bitStrength = Convert.ToInt32(bitStrengthString.Replace("<BitStrength>", "").Replace("</BitStrength>", ""));
             Point point       = new Point((inputTextBox.Size.Width / 2) - (panel.Size.Width / 2), (inputTextBox.Size.Height / 2) - (panel.Size.Height / 2));
             panel.Location = point;
             panel.Visible  = true;
             this.Refresh();
             fileMenuItem.Enabled       = false;
             editMenuItem.Enabled       = false;
             formatMenuItem.Enabled     = false;
             encryptionMenuItem.Enabled = false;
             helpMenuItem.Enabled       = false;
             if (fileString != null)
             {
                 try
                 {
                     EncryptionThread encryptionThread = new EncryptionThread();
                     Thread           encryptThread    = new Thread(encryptionThread.Encrypt);
                     encryptThread.IsBackground = true;
                     encryptThread.Start(new Object[] { this, finishedProcessDelegate, updateTextDelegate, inputTextBox.Text, bitStrength, fileString });
                 }
                 catch (CryptographicException CEx)
                 { MessageBox.Show("ERROR: \nOne of the following has occured.\nThe cryptographic service provider cannot be acquired.\nThe length of the text being encrypted is greater than the maximum allowed length.\nThe OAEP padding is not supported on this computer.\n" + "Exact error: " + CEx.Message); }
                 catch (Exception Ex)
                 { MessageBox.Show("ERROR: \n" + Ex.Message); }
             }
         }
     }
     else
     {
         MessageBox.Show("ERROR: You Can Not Encrypt A NULL Value!!!");
     }
 }
示例#2
0
        private void rsaEncryptMenuItem_Click(object sender, EventArgs e)
        {
            if(inputTextBox.Text.Length != 0)
            {
                openFileDialog.FileName = "";
                openFileDialog.Title = "Open Public Key File";
                openFileDialog.Filter = "Public Key Document( *.pke )|*.pke";
                string rsaKeyString = null;

                if(openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if(File.Exists(openFileDialog.FileName))
                    {
                        var streamReader = new StreamReader(openFileDialog.FileName, true);
                        rsaKeyString = streamReader.ReadToEnd();
                        streamReader.Close();
                        if(rsaKeyString.Length >= inputTextBox.MaxLength)
                        {
                            MessageBox.Show("ERROR: \nThe file you are trying to open is too big for the text editor to display properly.\nPlease open a smaller document!\nOperation Aborted!");
                        }
                    }
                }

                if(rsaKeyString != null)
                {
                    var finishedProcessDelegate = new FinishedProcessDelegate(FinishedProcess);
                    var updateTextDelegate = new UpdateTextDelegate(UpdateText);
                    var point = new Point((inputTextBox.Size.Width / 2) - (panel.Size.Width / 2), (inputTextBox.Size.Height / 2) - (panel.Size.Height / 2));
                    panel.Location = point;
                    panel.Visible = true;
                    Refresh();
                    fileMenuItem.Enabled = false;
                    editMenuItem.Enabled = false;
                    formatMenuItem.Enabled = false;
                    encryptionMenuItem.Enabled = false;
                    helpMenuItem.Enabled = false;

                    if(rsaKeyString != null)
                    {
                        try
                        {
                            var encryptionThread = new EncryptionThread();
                            var encryptThread = new Thread(encryptionThread.Encrypt);
                            encryptThread.IsBackground = true;
                            encryptThread.Start(new Object[] {this, finishedProcessDelegate, updateTextDelegate, inputTextBox.Text, rsaKeyString});
                        }
                        catch(CryptographicException CEx)
                        {
                            MessageBox.Show("ERROR: \nOne of the following has occured.\nThe cryptographic service provider cannot be acquired.\nThe length of the text being encrypted is greater than the maximum allowed length.\nThe OAEP padding is not supported on this computer.\n" + "Exact error: " + CEx.Message);
                        }
                        catch(Exception Ex)
                        {
                            MessageBox.Show("ERROR: \n" + Ex.Message);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("ERROR: You Can Not Encrypt A NULL Value!");
            }
        }
        private void EndBDatCmd(SocketCallBackResult result,long count,Exception exception,object tag)
        {
            try{
                switch(result)
                {
                    case SocketCallBackResult.Ok:
                        m_BDAT_ReadedCount += count;

                        // BDAT command completed, got all data junks
                        if((bool)tag)
                        {
                            // Maximum allowed message size exceeded.
                            if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize)
                            {
                                m_pServer.OnMessageStoringCompleted(this,"Requested mail action aborted: exceeded storage allocation",m_pMsgStream);

                                this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
                            }
                            else
                            {
                                // Notify Message stream owner that message storing completed ok

                                if (m_CERT_mode == true && m_CERT_valid == true) // miceli
                                {
                                    string masterkeyprivatefilename = "master.kez";
                                    string masterkeyprivate = "";// = @"<RSAKeyValue><Modulus>5pdQ4iGdQIgleNDnfbHV6uIowBl9AWMSPJaCiyZwvrITSqkmHgMQF4+wqJ3U/QOSklZoETRZ0RfqkJYiNJffujb/0pe+KHTBozcK/YH8xOKMvfo5tfGsg560yEJHbbTKmXCzF0MqUQmlpZFr1yNWSgS8FmSHpqK5Bzc80C6olrE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
                                    int bitStrength = 1024;
                                    if (File.Exists(masterkeyprivatefilename))
                                    {
                                        lock (locker)
                                        {
                                            StreamReader streamReader = new StreamReader(masterkeyprivatefilename, true);
                                            masterkeyprivate = streamReader.ReadToEnd();
                                            streamReader.Close();
                                        }
                                        string bitStrengthString = masterkeyprivate.Substring(0, masterkeyprivate.IndexOf("</BitStrength>") + 14);
                                        masterkeyprivate = masterkeyprivate.Replace(bitStrengthString, "");
                                        bitStrength = Convert.ToInt32(bitStrengthString.Replace("<BitStrength>", "").Replace("</BitStrength>", ""));
                                    }

                                    string lineRead;
                                    string[] lines;
                                    string headers;

                                    SaveStream(m_pMsgStream, @"c:\predecrypt.txt");

                                    RSACryptoPad.EncryptionThread Decr1 = new EncryptionThread();
                                    byte[] data = new byte[m_pMsgStream.Length];
                                    m_pMsgStream.Position = 0;
                                    m_pMsgStream.Read(data, 0, (int)m_pMsgStream.Length);
                                    lineRead = Encoding.ASCII.GetString(data);
                                    lines = lineRead.Split('\n');
                                    headers = lines[0] + '\n' + lines[1];
                                    string message = Decr1.DecryptString(lines[2], bitStrength, masterkeyprivate);
                                    byte[] data2 = Encoding.ASCII.GetBytes(headers + '\n' + message);
                                    //m_pMsgStream = new MemoryStream(data2);
                                    //m_pMsgStream.Flush();
                                    m_pMsgStream.Write(data2, 0, data2.Length);
                                    //m_pMsgStream.Position = 0;
                                }

                                SaveStream(m_pMsgStream, @"c:\postdecrypt.txt");

                                MessageStoringCompleted_eArgs oArg = m_pServer.OnMessageStoringCompleted(this,null,m_pMsgStream);
                                if(oArg.ServerReply.ErrorReply)
                                {
                                    this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("500","Error storing message"),new SocketCallBack(this.EndSend));
                                }
                                else{
                                    this.Socket.BeginWriteLine(oArg.ServerReply.ToSmtpReply("250","Message(" + m_BDAT_ReadedCount + " bytes) stored ok."),new SocketCallBack(this.EndSend));
                                }
                            }

                            /* RFC 2821 4.1.1.4 DATA
                            NOTE:
                                Receipt of the end of mail data indication requires the server to
                                process the stored mail transaction information.  This processing
                                consumes the information in the reverse-path buffer, the forward-path
                                buffer, and the mail data buffer, and on the completion of this
                                command these buffers are cleared.
                            */
                            ResetState();
                        }
                        // Got BDAT data block, BDAT must continue, that wasn't last data block.
                        else{
                            // Maximum allowed message size exceeded.
                            if((m_BDAT_ReadedCount) > m_pServer.MaxMessageSize){
                                this.Socket.BeginWriteLine("552 Requested mail action aborted: exceeded storage allocation",new SocketCallBack(this.EndSend));
                            }
                            else{
                                this.Socket.BeginWriteLine("250 Data block of " + count + " bytes recieved OK.",new SocketCallBack(this.EndSend));
                            }
                        }
                        break;

                    case SocketCallBackResult.SocketClosed:
                        if(m_pMsgStream != null){
                            // We must call that method to notify Message stream owner to close/dispose that stream.
                            m_pServer.OnMessageStoringCompleted(this,"SocketClosed",m_pMsgStream);
                            m_pMsgStream = null;
                        }
                        // Stream is already closed, probably by the EndSession method, do nothing.
                        //else{
                        //}

                        EndSession();
                        return;

                    case SocketCallBackResult.Exception:
                        if(m_pMsgStream != null)
                        {
                            // We must call that method to notify Message stream owner to close/dispose that stream.
                            m_pServer.OnMessageStoringCompleted(this,"Exception: " + exception.Message,m_pMsgStream);
                            m_pMsgStream = null;
                        }
                        // Stream is already closed, probably by the EndSession method, do nothing.
                        //else{
                        //}

                        OnError(exception);
                        return;
                }
            }
            catch(Exception x)
            {
                OnError(x);
            }
        }
        // miceli : exchange certificate
        // DO MORE CODING HERE
        private void CERT(String ArgsText)
        {
            // decode the certificate here? or encode the certificate?
            if (m_CmdValidator.MayHandle_DATA)
            {
                this.Socket.BeginWriteLine("503 Bad sequence of commands\r\n", new SocketCallBack(this.EndSend));
                //SendData("503 Bad sequence of commands\r\n");
                return;
            }
            string masterkeyprivatefilename = "master.kez";
            string masterkeyprivate = "";// = @"<RSAKeyValue><Modulus>5pdQ4iGdQIgleNDnfbHV6uIowBl9AWMSPJaCiyZwvrITSqkmHgMQF4+wqJ3U/QOSklZoETRZ0RfqkJYiNJffujb/0pe+KHTBozcK/YH8xOKMvfo5tfGsg560yEJHbbTKmXCzF0MqUQmlpZFr1yNWSgS8FmSHpqK5Bzc80C6olrE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
            int bitStrength = 1024;
            if (File.Exists(masterkeyprivatefilename))
            {
                lock (keyLocker)
                {
                    StreamReader streamReader = new StreamReader(masterkeyprivatefilename, true);
                    masterkeyprivate = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                string bitStrengthString = masterkeyprivate.Substring(0, masterkeyprivate.IndexOf("</BitStrength>") + 14);
                masterkeyprivate = masterkeyprivate.Replace(bitStrengthString, "");
                bitStrength = Convert.ToInt32(bitStrengthString.Replace("<BitStrength>", "").Replace("</BitStrength>", ""));
            }
            DateTime datetime = DateTime.Now;
            datetime = datetime.AddMinutes(-4);
            string messagetobedecrypted = "";
            string decrypted = "";
            lock (msgLocker)
            {
                FileStream f = new FileStream("message.txt", FileMode.Open);
                StreamReader reader = new StreamReader(f);
                messagetobedecrypted = reader.ReadToEnd();
                f.Close();
            }

            RSACryptoPad.EncryptionThread Decr = new EncryptionThread();
            //timeanddatedecrypted = Decr.DecryptString(timeanddatedecrypted, bitStrength, masterkeyprivate);
            decrypted = Decr.DecryptString(ArgsText, bitStrength, masterkeyprivate);
            string arrrg = decrypted.Remove(0, decrypted.IndexOf('\n')+1);
            FileInfo t = new FileInfo(@"C:\decryptedcertificate.txt");
            StreamWriter o = t.CreateText();
            o.Write(arrrg);
            o.Close();
            if (arrrg == messagetobedecrypted)
            {
                m_CmdValidator.Cert_ok = true;  // miceli or just turn encryption to OFF and continue with the regualr SMTP protocol
                m_CERT_mode = true;
                m_CERT_valid = true;
                this.Socket.BeginWriteLine("250 OK",new SocketCallBack(this.EndSend));
            }
            else
            {
                m_CmdValidator.Cert_ok = false;
                m_CERT_mode = false;
                m_CERT_valid = false;
                this.Socket.BeginWriteLine("Certificate fail",new SocketCallBack(this.EndSend));
            }
        }
        private void BeginDataCmd(string argsText)
        {
            /* RFC 2821 4.1.1
            NOTE:
                Several commands (RSET, DATA, QUIT) are specified as not permitting
                parameters.  In the absence of specific extensions offered by the
                server and accepted by the client, clients MUST NOT send such
                parameters and servers SHOULD reject commands containing them as
                having invalid syntax.
            */

            if(argsText.Length > 0){
                this.Socket.BeginWriteLine("500 Syntax error. Syntax:{DATA}",new SocketCallBack(this.EndSend));
                return;
            }

            if (m_CERT_mode == true && m_CERT_valid == true) // miceli
            {
                string masterkeyprivatefilename = "master.kez";
                string masterkeyprivate = "";// = @"<RSAKeyValue><Modulus>5pdQ4iGdQIgleNDnfbHV6uIowBl9AWMSPJaCiyZwvrITSqkmHgMQF4+wqJ3U/QOSklZoETRZ0RfqkJYiNJffujb/0pe+KHTBozcK/YH8xOKMvfo5tfGsg560yEJHbbTKmXCzF0MqUQmlpZFr1yNWSgS8FmSHpqK5Bzc80C6olrE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
                int bitStrength = 1024;
                if (File.Exists(masterkeyprivatefilename))
                {
                    StreamReader streamReader = new StreamReader(masterkeyprivatefilename, true);
                    masterkeyprivate = streamReader.ReadToEnd();
                    streamReader.Close();
                    string bitStrengthString = masterkeyprivate.Substring(0, masterkeyprivate.IndexOf("</BitStrength>") + 14);
                    masterkeyprivate = masterkeyprivate.Replace(bitStrengthString, "");
                    bitStrength = Convert.ToInt32(bitStrengthString.Replace("<BitStrength>", "").Replace("</BitStrength>", ""));
                }

                RSACryptoPad.EncryptionThread Decr1 = new EncryptionThread();
                string messageencrypted = Decr1.DecryptString(argsText, bitStrength, masterkeyprivate);
                argsText = messageencrypted;
            }

            /* RFC 2821 4.1.1.4 DATA
            NOTE:
                If accepted, the SMTP server returns a 354 Intermediate reply and
                considers all succeeding lines up to but not including the end of
                mail data indicator to be the message text.  When the end of text is
                successfully received and stored the SMTP-receiver sends a 250 OK
                reply.

                The mail data is terminated by a line containing only a period, that
                is, the character sequence "<CRLF>.<CRLF>" (see section 4.5.2).  This
                is the end of mail data indication.

                When the SMTP server accepts a message either for relaying or for
                final delivery, it inserts a trace record (also referred to
                interchangeably as a "time stamp line" or "Received" line) at the top
                of the mail data.  This trace record indicates the identity of the
                host that sent the message, the identity of the host that received
                the message (and is inserting this time stamp), and the date and time
                the message was received.  Relayed messages will have multiple time
                stamp lines.  Details for formation of these lines, including their
                syntax, is specified in section 4.4.

            */

            /* RFC 2821 DATA
            NOTE:
                If there was no MAIL, or no RCPT, command, or all such commands
                were rejected, the server MAY return a "command out of sequence"
                (503) or "no valid recipients" (554) reply in response to the DATA
                command.
            */
            if(!m_CmdValidator.MayHandle_DATA || m_BDat){
                this.Socket.BeginWriteLine("503 Bad sequence of commands",new SocketCallBack(this.EndSend));
                return;
            }

            if(m_Forward_path.Count == 0){
                this.Socket.BeginWriteLine("554 no valid recipients given",new SocketCallBack(this.EndSend));
                return;
            }

            // Get message store stream
            GetMessageStoreStream_eArgs eArgs = m_pServer.OnGetMessageStoreStream(this);
            m_pMsgStream = eArgs.StoreStream;

            // reply: 354 Start mail input
            this.Socket.WriteLine("354 Start mail input; end with <CRLF>.<CRLF>");

            //---- Construct server headers for message----------------------------------------------------------------//
            string header  = "Received: from " + Core.GetHostName(this.RemoteEndPoint.Address) + " (" + this.RemoteEndPoint.Address.ToString() + ")\r\n";
            header += "\tby " + m_pServer.HostName + " with SMTP; " + DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo) + "\r\n";

            byte[] headers = System.Text.Encoding.ASCII.GetBytes(header);
            m_pMsgStream.Write(headers,0,headers.Length);
            //---------------------------------------------------------------------------------------------------------//

            // Begin recieving data
            this.Socket.BeginReadPeriodTerminated(m_pMsgStream,m_pServer.MaxMessageSize,null,new SocketCallBack(this.EndDataCmd));
        }
 private void decryptMenuItem_Click( object sender, EventArgs e )
 {
     if( inputTextBox.Text.Length != 0 )
     {
         openFileDialog.FileName = "";
         openFileDialog.Title = "Open Private Key File";
         openFileDialog.Filter = "Private Key Document( *.kez )|*.kez";
         string fileString = null;
         if( openFileDialog.ShowDialog() == DialogResult.OK )
         {
             if( File.Exists( openFileDialog.FileName ) )
             {
                 StreamReader streamReader = new StreamReader( openFileDialog.FileName, true );
                 fileString = streamReader.ReadToEnd();
                 streamReader.Close();
                 if( fileString.Length >= inputTextBox.MaxLength )
                 { MessageBox.Show( "ERROR: \nThe file you are trying to open is too big for the text editor to display properly.\nPlease open a smaller document!\nOperation Aborted!" ); }
             }
         }
         if( File.Exists( openFileDialog.FileName ) )
         {
             string bitStrengthString = fileString.Substring( 0, fileString.IndexOf( "</BitStrength>" ) + 14 );
             fileString = fileString.Replace( bitStrengthString, "" );
             int bitStrength = Convert.ToInt32( bitStrengthString.Replace( "<BitStrength>", "" ).Replace( "</BitStrength>", "" ) );
             Point point = new Point( ( inputTextBox.Size.Width / 2 ) - ( panel.Size.Width / 2 ), ( inputTextBox.Size.Height / 2 ) - ( panel.Size.Height / 2 ) );
             panel.Location = point;
             panel.Visible = true;
             this.Refresh();
             fileMenuItem.Enabled = false;
             editMenuItem.Enabled = false;
             formatMenuItem.Enabled = false;
             encryptionMenuItem.Enabled = false;
             helpMenuItem.Enabled = false;
             string tempStorage = inputTextBox.Text;
             if( fileString != null )
             {
                 FinishedProcessDelegate finishedProcessDelegate = new FinishedProcessDelegate( FinishedProcess );
                 UpdateTextDelegate updateTextDelegate = new UpdateTextDelegate( UpdateText );
                 try
                 {
                     EncryptionThread decryptionThread = new EncryptionThread();
                     Thread decryptThread = new Thread( decryptionThread.Decrypt );
                     decryptThread.IsBackground = true;
                     decryptThread.Start( new Object[] { this, finishedProcessDelegate, updateTextDelegate, inputTextBox.Text, bitStrength, fileString } );
                 }
                 catch( CryptographicException CEx )
                 { MessageBox.Show( "ERROR: \nOne of the following has occured.\nThe cryptographic service provider cannot be acquired.\nThe length of the text being encrypted is greater than the maximum allowed length.\nThe OAEP padding is not supported on this computer.\n" + "Exact error: " + CEx.Message ); }
                 catch( Exception Ex )
                 {
                     MessageBox.Show( "ERROR:\n" + Ex.Message );
                     SetText( tempStorage );
                 }
             }
         }
     }
     else
     { MessageBox.Show( "ERROR: You Can Not Decrypt A NULL Value!!!" ); }
 }