[C#] Créer une application pour crypter les fichiers texte + release de dll

Paradise'

Premium
Inscription
30 Juin 2013
Messages
4 259
Réactions
4 384
Points
20 795
http://reality-gaming.fr/proxy.php?image=http%3A%2F%2Fimage.noelshack.com%2Ffichiers%2F2014%2F28%2F1404831415-gtp-gif.gif&hash=29286e9f966ee2d005ed9c5836507105
La GTP vous propose un nouveau tutoriel, réalisé par Boosterz GTP


" [C#] Créer une application pour crypter les fichiers texte + release de dll "
Bonne lecture
http://reality-gaming.fr/proxy.php?image=http%3A%2F%2Fi.imgur.com%2Ff2z1hsY.png&hash=fec836898435df57c0c59b77e2048422 !


separator.png

Avant de commencé il vous faudra cette extension d'application ( dll ) qui vous facilitera la tache.
Voila les liens de téléchargement :
| |

Donc le design principal, celui que j'utilise est celui là :

c89fb25ffd073c0bed7ba028349f35b3.png


Alors pour faciliter voici le nom des éléments dans mon code :

Dans la toolStrip :
Il vous faut mettre un DropDownButton dans le quel on mettra deux items :
RC4 : rC4ToolStripMenuItem
RSA : rSAToolStripMenuItem

Ensuite, les items de la form :
Les labels ne sont pas à changer sauf celui de la " key " que on appel : lblKey
Ensuite les textbox.
Celle ou il y aura le chemin du fichier texte : txtChemin
La textbox ou soit on créera le fichier texte ou sera afficher le fichier texte ouvert : txtTxt ( Original hein ? :trollface: )
Et pour finir la ou générera la key : txtKey
Ensuite les items non classé on va dire :
Le numéricupdown : numericUpDown
La checkbox : chkCre
Puis pour finir les boutons :
... : btnCherche
Crypter : btnEncrypt
Décrypter : btnDecrypt
Clear : btnClear
Fermer : btnFermer
Générer clef : btnGenererKey

Voila les items finit.

separator.png


Donc on commence simplement par
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Collections;
using Cryptext;

Vous devez bien évidement avoir ajouter Cryptext.dll
Puis vous ajoutez sa :
Code:
        private static int _keyLength = 0;
        private String _key = null;
        private String _cryptedText = "";
        private static Boolean _flag = false;
        private String _randomKey = "";

        private static String APPLICATION_NAME = "Text Encrypter Decrypter";
3825e4ac941890b7d07f3993f66915b1.png


Puis dans la form 1 Load ( à l'ouverture du logiciel ) :
Code:
            btnEncrypt.Enabled = false;
            btnDecrypt.Enabled = false;
            _flag = true;

Puis ensuite vous mettez ceci :
Code:
        public String ReadFullFileData(string fileName)
        {
            TextReader tr = null;
            try
            {
                tr = File.OpenText(fileName);

                if (tr != null)
                    return tr.ReadToEnd();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                tr.Close();
            }

            return null;
        }

c461717ec03e9d0390e3c80b96e0714d.png


Ensuite afin de ne pas mettre une openfiledialog on peut faire à la place avec ce code :
Code:
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Title = title;
            fileDialog.Filter = "Fichier texte (*.txt)|*.txt";

            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtChemin.Text = fileDialog.FileName;
                string dataToEncrypt = ReadFullFileData(fileDialog.FileName);
                txtTxt.Text = dataToEncrypt;
                chkCre.Checked = true;
            }
            else
            {
                return;
            }

Pareil avec une savefiledialog.
Code:
            TextWriter tw = null;
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = title;
                saveFileDialog.Filter = "Fichier texte (*.txt)|*.txt";
                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tw = File.CreateText(saveFileDialog.FileName);
                    tw.WriteLine(txtTxt.Text);
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                tw.Close();
            }

e65dd9b59a276ddbcc6c3bc9a7ce0317.png


Ensuite la fonction pour random la clef de cryptage.
Code:
        public static String RandomKeyString()
        {
            StringBuilder builder = new StringBuilder();
            Random r = new Random();
            char ch;
            int size = r.Next(10, 20);

            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(r.Next(65, 122));
                builder.Append(ch);
            }

            return builder.ToString();
        }

Puis le code dans le bouton pour random la clef :
Code:
            if (_flag)
            {
                lblKey.Text = "RC4 Encryption Key";
                _randomKey = RandomKeyString();
                txtKey.Text = _randomKey;
            }
            else
            {
                _key = RSAEncryptionDecryption.RSAGenerateKey(_keyLength);
                string bitStrengthString = _key.Substring(0, _key.IndexOf("</BitStrength>") + 14);
                _key = _key.Replace(bitStrengthString, "");
                lblKey.Text = "RSA Encryption Key";
                txtKey.Text = _key;
            }

400bb8e6a083e55a2c2fd70a15e3b7f1.png


Ensuite le bouton ' ... '
Code:
            OpenFile("Ouvrir un fichier texte");
            btnEncrypt.Enabled = true;
            btnDecrypt.Enabled = true;
Puis on met la RC4 pour crypté et décrypté :
Code:
        public void RC4Encryption()
        {
            RC4EncryptionDecryption rc4Enc = new RC4EncryptionDecryption();
            rc4Enc.EncryptionKey = _randomKey;
            lblKey.Text = "RC4 Encryption Key";
            txtKey.Text = _randomKey;
            rc4Enc.InClearText = txtTxt.Text;
            rc4Enc.RC4Encryption();
            this._cryptedText = rc4Enc.CryptedText;
            txtTxt.Clear();
            txtTxt.Text = this._cryptedText;
        }
        public void RC4Decryption()
        {
            RC4EncryptionDecryption rc4Enc = new RC4EncryptionDecryption();
            rc4Enc.EncryptionKey = _randomKey;

            lblKey.Text = "RC4 Decryption Key";
            txtKey.Text = _randomKey;

            rc4Enc.CryptedText = txtTxt.Text;
            rc4Enc.RC4Decryption();
            txtTxt.Clear();
            txtTxt.Text = rc4Enc.InClearText;
        }
b44874a3b45e350de48258a097a8d7a9.png

Maintenant le RSA crypté et décrypté :
Code:
        public void RSAEncryption()
        {
            _keyLength = Convert.ToInt32(numericUpDown.Value.ToString());
            string encryptedString = RSAEncryptionDecryption.RSAEncryption(txtTxt.Text, _keyLength, _key);
            lblKey.Text = "RSA Encryption Key";
            txtKey.Text = _key;
            txtTxt.Clear();
            txtTxt.Text = encryptedString;
            chkCre.Checked = true;
        }
        public void RSADecryption()
        {
            string decryptedString = RSAEncryptionDecryption.RSADecryption(txtTxt.Text, _keyLength, _key);
            txtTxt.Clear();
            txtTxt.Text = decryptedString;
        }
097fca4a8be78cec96f93a3fa514020f.png


Puis le bouton crypté :
Code:
            try
            {
                if (String.IsNullOrEmpty(txtKey.Text))
                {
                    MessageBox.Show("You must generate key first to encrypt or decrypt text.", APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else if (!String.IsNullOrEmpty(txtKey.Text))
                {
                    if (txtTxt.Text != null && !chkCre.Checked)
                    {
                        if (_flag)
                        {
                            RC4Encryption();
                        }
                        else
                        {
                            RSAEncryption();
                        }

                        DialogResult result = MessageBox.Show("Want to save encrypted text to file?", APPLICATION_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        if (result == System.Windows.Forms.DialogResult.Yes)
                        {
                            SaveFile("Save a encrypted text to file");
                        }
                        else
                        {
                            return;
                        }
                    }
                    else if (chkCre.Checked && txtTxt.Text != null)
                    {
                        if (_flag)
                        {
                            RC4Encryption();
                        }
                        else
                        {
                            RSAEncryption();
                        }

                        DialogResult result = MessageBox.Show("Want to save encrypted text to file?", APPLICATION_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                        if (result == System.Windows.Forms.DialogResult.Yes)
                        {
                            SaveFile("Save a encrypted text to file");
                        }
                        else
                        {
                            return;
                        }
                    }
                }

Puis le bouton décrypté :
Code:
            try
            {
                if (txtTxt.Text != null && !chkCre.Checked)
                {
                    OpenFile("Open A Encrypted File To Decrypt");

                    if (_flag)
                    {
                        RC4Decryption();
                    }
                    else
                    {
                        RSADecryption();
                    }

                    DialogResult result = MessageBox.Show("Want to save decrypted text to file?", APPLICATION_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveFile("Save a decrypted text to file");
                    }
                    else
                    {
                        return;
                    }
                }
                else if (chkCre.Checked && txtTxt.Text != null)
                {
                    if (_flag)
                    {
                        RC4Decryption();
                    }
                    else
                    {
                        RSADecryption();
                    }

                    DialogResult result = MessageBox.Show("Want to save decrypted text to file?", APPLICATION_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        SaveFile("Save a decrypted text to file");
                    }
                    else
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

Puis le code de la petite checkbox.
Code:
            if (chkCre.Checked)
            {
                btnEncrypt.Enabled = true;
                btnDecrypt.Enabled = true;
            }
            else
            {
                btnEncrypt.Enabled = false;
                btnDecrypt.Enabled = false;
            }

Bouton clear :
Code:
            txtTxt.Clear();
            txtKey.Clear();

Puis le bouton quitter :
Code:
            Application.Exit();

6df5b2e0fd6df6e210ae364cc4c1f8fa.png


Ensuite pour finir on met le code des deux boutons de la toolstrip :
RC4 :
Code:
            _flag = true;
RSA :
Code:
            _flag = false;
separator.png


Attention ! :
Pour décrypter le fichier texte il vous faut bien évidement la même key que le cryptage.

Voila ce tutoriel ce finit la.
Donc je vous partage la source :
| |

Merci de votre lecture.
Je remercie @Lyrix GTP pour le contour des images.
 
D

delete221380

Bien joué l'ami, mais tu sais il existe un dll dans VS appeler Cryptographie qui permet une encryption plus pousser :)
Mais c'est un bon début jeune padawan :love:
 
Haut