Encrypto / Decrypto ConnectionString Örnegi



Encrypto / Decrypto ConnectionString Örnegi

Bu örneğimizde verileri hdd encrypto şeklinde kaydetmeyi ve decrypto şeklinde de geri okumayı işledim

Bu örneğin çalışması için bir adet aspx sayfası ve iki adet de App_Code klasöründe class dosyasına ihtiyacımız vardır tüm kodlar aşagıda komple olarak verilmiştir. Umarım istifade edersiniz.

[aspx] Sayfası

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeFile="EncryptoOrDecrypto.aspx.cs" Inherits="EncryptoOrDecrypto" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Encrypto / Decrypto ConnectionString Örnegi</title>

</head>

<body>

    <form id="form1" runat="server">

   

    <div style="margin: 10 10 10 10; padding: 10 10 10 10">

        <table cellpadding="1"  cellspacing="1" style="width: 600px">

            <tr>

                <td style="width: 180px">

                    <asp:Label ID="lblServer" runat="server" Text="SQL Server"></asp:Label>

                </td>

                <td>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1"

                        runat="server"

                        ControlToValidate="txtServer" 

                        ErrorMessage="*"></asp:RequiredFieldValidator>

                </td>

                <td>

                    <asp:TextBox ID="txtServer" runat="server" Width="100%"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td class="style1" style="width: 180px">

                    <asp:Label ID="lblData" runat="server" Text="Veritabanı İsmi"></asp:Label>

                </td>

                <td>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2"

                        runat="server"

                        ControlToValidate="txtData"  

                        ErrorMessage="*"></asp:RequiredFieldValidator>

                </td>

                <td>

                    <asp:TextBox ID="txtData" runat="server" Width="100%"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td class="style1" style="width: 180px">

                    <asp:Label ID="lblUserID" runat="server" Text="User ID"></asp:Label>

                </td>

                <td>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3"

                        runat="server"

                        ControlToValidate="txtUserId"  

                        ErrorMessage="*"></asp:RequiredFieldValidator>

                </td>

                <td>

                    <asp:TextBox ID="txtUserId" runat="server" Width="100%"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td class="style1" style="width: 180px">

                    <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>

                </td>

                <td>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4"

                        runat="server"

                        ControlToValidate="txtPassword"

                        ErrorMessage="*"></asp:RequiredFieldValidator>

                </td>

                <td>

                    <asp:TextBox ID="txtPassword" runat="server" Width="100%"></asp:TextBox>

                </td>

            </tr>

              <tr>

                <td class="style1" style="width:180px">

                    <asp:Label ID="lblKey" runat="server" Text="Key"></asp:Label>

                </td>

                <td>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5"

                        runat="server"

                        ControlToValidate="txtKey" 

                        ErrorMessage="*"></asp:RequiredFieldValidator>

                </td>

                <td>

                    <asp:TextBox ID="txtKey"

                        runat="server"

                        Width="100%"

                        MaxLength="21"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td class="style1" colspan="3">

                    <asp:TextBox ID="txtCrypto"

                        runat="server"

                        Height="123px"

                        TextMode="MultiLine"

                        ReadOnly="true"

                        Width="100%"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td class="style1" style="width: 180px">

                    &nbsp;

                    <asp:Label ID="lblMessage" runat="server"></asp:Label>

                </td>

                <td>

                    &nbsp;</td>

                <td>

                    <asp:Button ID="btnCrypto" runat="server" Text="Şifrele"

                        onclick="btnCrypto_Click" Width="100%" />

                </td>

            </tr>

         </table>

    </div>

   

    </form>

</body>

</html>

 

 [C#] Code Behind Sayfası

using System;

using System.Collections.Generic;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

 

public partial class EncryptoOrDecrypto : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void btnCrypto_Click(object sender, EventArgs e)

    {

        Cryption Cryp = new Cryption();

        if (btnCrypto.Text == "Şifrele")

        {

            Cryp.EncryptionKey = this.txtKey.Text;

            Cryp.InClearText = "data source=" + txtServer.Text +

                               ";initial catalog=" + txtData.Text +

                               ";persist security info=true;user id=" + txtUserId.Text +

                               ";password=" + txtPassword.Text +

                               ";packet size=4096";

            //Bu metod veriyi Encriptolar. yani şifreler

            Cryp.Encrypt();

 

            txtCrypto.Text = Cryp.CryptedText;

            btnCrypto.Text = "Şifre çöz";

            if (CreateOrRecordEncryptionData(txtCrypto.Text))

            {

                RecordDataKey(txtKey.Text);

            };

        }

        else

        {

            String FilePath;

 

            FilePath = Server.MapPath(".");

 

            FileInfo bankayi = new FileInfo(FilePath + "\\App_Code\\Key");

            Cryp.EncryptionKey = ReadData(bankayi.ToString());

 

            FileInfo EncrypConnection = new FileInfo(FilePath + "\\App_Code\\EncrypConnection");

            Cryp.CryptedText = ReadData(EncrypConnection.ToString());

 

            //Bu metod veriyi Decrypto eder. Yani Şifresini çözer

            Cryp.Decrypt();

 

            txtCrypto.Text = Cryp.CryptedText;

            btnCrypto.Text = "Şifrele";

        }

    }

 

    //Bu metod diskteki Encrypto lu veriyi alır.

    private bool CreateOrRecordEncryptionData(string text)

    {

        try

        {

            String FilePath;

            FilePath = Server.MapPath(".");

            FileInfo t = new FileInfo(FilePath + "\\App_Code\\EncrypConnection");

 

            StreamWriter Tex = t.CreateText();

            Tex.WriteLine(text);

            Tex.Write(Tex.NewLine);

            Tex.Close();

 

            return true;

        }

        catch

        {

            return false;

        }

    }

    //Bu metod diskten Encriptolu Key verisini alır

    private bool RecordDataKey(string key)

    {

        try

        {

            String FilePath;

            FilePath = Server.MapPath(".");

            FileInfo t = new FileInfo(FilePath + "\\App_Code\\Key");

 

            StreamWriter Key = t.CreateText();

            Key.WriteLine(key);

            Key.WriteLine(Key.NewLine);

            Key.Close();

 

            return true;

        }

        catch

        {

            return false;

        }

    }

    //Bu metod diskten alınan dosyayı okur ve geri döndürür.

    private string ReadData(string path)

    {

        string line = "";

        string strDecrypto = "";

        try

        {

            using (StreamReader sr = new StreamReader(File.Open(path, FileMode.Open)))

            {

                while ((line = sr.ReadLine()) != "")

                {

                    strDecrypto += line;

                }

            }

            return strDecrypto;

        }

        catch (Exception ex)

        {

            return ex.Message.ToString();

        }

    }

}


[App_Code]


[DbUtils.cs]

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Data.SqlClient;

using System.Net.Mail;

using System.Net;

using System.IO;

using System.Net.Mime;

using System.Text;

using System.ServiceModel.Channels;

using System.EnterpriseServices;

 

 

public class DbUtils

{

    public DbUtils()

    {

    }

 

   

    //Bu metod Decripto eder ve SQL e connection açar

    public static SqlConnection CreateConnection(string connectionString)

    {

        return new SqlConnection(connectionString);

    }

 

    public static SqlConnection CreateConnection()

    {

        return CreateConnection(ConnectionString);

    }

    //Bu metod programın olmuş olduğu App_Code dizinden Encriptolu Key ve ConnectionStringi alır

    public static string ConnectionString

    {

        get

        {

            String FilePath;

            FilePath = HttpContext.Current.Server.MapPath(".");

 

            Cryption Cryp = new Cryption();

 

            FileInfo bankayi = new FileInfo(FilePath + "\\App_Code\\Key");

            Cryp.EncryptionKey = ReadData(bankayi.ToString());

 

            FileInfo EncrypConnection = new FileInfo(FilePath + "\\App_Code\\EncrypConnection");

            Cryp.CryptedText = ReadData(EncrypConnection.ToString());

            //Bu metod Encriptolu veri Decripto eder. yani şifresini çözer

            Cryp.Decrypt();

 

            HttpContext.Current.Session["ConnectionString"] = Cryp.CryptedText;

            return Cryp.CryptedText;

        }

    }

    //Bu metod Encripto lu Key i alır.

    private bool RecordDataKey(string key)

    {

        try

        {

            String FilePath;

            FilePath = HttpContext.Current.Server.MapPath(".");

            FileInfo t = new FileInfo(FilePath + "\\App_Code\\Key");

 

            StreamWriter Key = t.CreateText();

            Key.WriteLine(key);

            Key.WriteLine(Key.NewLine);

            Key.Close();

 

            return true;

        }

        catch

        {

            return false;

        }

    }

    //Bu metod decripto edilmiş olan veriyi döndürür.

    private static string ReadData(string path)

    {

        string line = "";

        string strDecrypto = "";

        try

        {

            using (StreamReader sr = new StreamReader(File.Open(path, FileMode.Open)))

            {

                while ((line = sr.ReadLine()) != "")

                {

                    strDecrypto += line;

                }

            }

            return strDecrypto;

        }

        catch (Exception ex)

        {

            return ex.Message.ToString();

        }

    }

}

 

 

[Cryption.cs]

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Text;

 

public class Cryption

{

    public Cryption()

    {

    }

 

    #region Public Method

 

    public bool Encrypt()

    {

        //

        // toRet fonksiyonu retcode saklamak için kullanılacak

        //

        bool toRet = true;

 

        try

        {

            //

            // kullanılan endeksler

            //

            long i = 0;

            long j = 0;

 

            //

            // Geçici byte dizi giriş dizesi

            //

            Encoding enc_default = Encoding.Default;

            byte[] input = enc_default.GetBytes(this.m_sInClearText);

 

            //

            // Çıkış byte array

            //

            byte[] output = new byte[input.Length];

 

            //

            // M_nBoxLen Yerel kopyası

            //

            byte[] n_LocBox = new byte[m_nBoxLen];

            this.m_nBox.CopyTo(n_LocBox, 0);

 

            long ChipherLen = input.Length + 1;

 

            //

            // Alghoritmayı çalıştır

            //

            for (long offset = 0; offset < input.Length; offset++)

            {

                i = (i + 1) % m_nBoxLen;

                j = (j + n_LocBox[i]) % m_nBoxLen;

                byte temp = n_LocBox[i];

                n_LocBox[i] = n_LocBox[j];

                n_LocBox[j] = temp;

                byte a = input[offset];

                byte b = n_LocBox[(n_LocBox[i] + n_LocBox[j]) % m_nBoxLen];

                output[offset] = (byte)((int)a ^ (int)b);

            }

 

            //

            // Çıkış string (CryptedText)

            //

            char[] outarrchar = new char[enc_default.GetCharCount(output, 0, output.Length)];

            enc_default.GetChars(output, 0, output.Length, outarrchar, 0);

            this.m_sCryptedText = new string(outarrchar);

        }

        catch

        {

            //

            // hata oluştu - false retcode ayarlayın.

            //

            toRet = false;

        }

 

        //

        // geri retcode dondur

        //

        return (toRet);

 

    }

 

    /// <summary>

    ///Şifreyi çöz CryptedText InClearText EncriptionKey kullanarak

    /// </summary>

    /// <returns>başarılı ise true başarısız ise false döndür</returns>

    public bool Decrypt()

    {

        //

        // toRet fonksiyonu retcode saklamak için kullanılacak

        //

        bool toRet = true;

 

        try

        {

            this.m_sInClearText = this.m_sCryptedText;

            m_sCryptedText = "";

            if (toRet = Encrypt())

            {

                m_sInClearText = m_sCryptedText;

            }

 

        }

        catch

        {

            //

            // hata oluştu - false retcode ayarlayın.

            //

            toRet = false;

        }

 

        //

        // retcode döndürün

        //

        return toRet;

    }

 

    #endregion

 

    #region Prop definitions

    /// <summary>

    /// Şifreleme Anahtarı ayarlama

    /// </summary>

    public string EncryptionKey

    {

        get

        {

            return (this.m_sEncryptionKey);

        }

        set

        {

            //

            //atama değeri yalnızca yeni bir değerdir

            //

            if (this.m_sEncryptionKey != value)

            {

                this.m_sEncryptionKey = value;

 

                //

                //   M_nBox doldurmak için kullanılır

                //

                long index2 = 0;

 

                //

                // Iki farklı kodlama oluştur

                //

                Encoding ascii = Encoding.ASCII;

                Encoding unicode = Encoding.Unicode;

 

                //

                // Unicode ANSI kadar şifreleme anahtarı dönüşümü Gerçekleştir

                //

                byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicode.GetBytes(this.m_sEncryptionKey));

 

                //

                // Convert byte yeni bir char [] [] içine ve sonra dizeye

                //

 

                char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];

                ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);

                this.m_sEncryptionKeyAscii = new string(asciiChars);

               

                long KeyLen = m_sEncryptionKey.Length;

 

                //

                // İlk Loop

                //

                for (long count = 0; count < m_nBoxLen; count++)

                {

                    this.m_nBox[count] = (byte)count;

                }

 

                //

                // Ikinci Loop

                //

                for (long count = 0; count < m_nBoxLen; count++)

                {

                    index2 = (index2 + m_nBox[count] + asciiChars[count % KeyLen]) % m_nBoxLen;

                    byte temp = m_nBox[count];

                    m_nBox[count] = m_nBox[index2];

                    m_nBox[index2] = temp;

                }

 

            }

        }

    }

 

    public string InClearText

    {

        get

        {

            return (this.m_sInClearText);

        }

        set

        {

            //

            // atama değeri yalnızca yeni bir değerdir

            //

            if (this.m_sInClearText != value)

            {

                this.m_sInClearText = value;

            }

        }

    }

 

    public string CryptedText

    {

        get

        {

            return (this.m_sCryptedText);

        }

        set

        {

            //

            // atama değeri yalnızca yeni bir değerdir

            //

            if (this.m_sCryptedText != value)

            {

                this.m_sCryptedText = value;

            }

        }

    }

    #endregion

 

    #region Private Fields

 

    //

    // Şifreleme anahtarı - Unicode & Ascii sürümü

    //

    private string m_sEncryptionKey = "";

    private string m_sEncryptionKeyAscii = "";

    //

    // Şifreleme Anahtar ilişkilidir

    //

    protected byte[] m_nBox = new byte[m_nBoxLen];

    static public long m_nBoxLen = 255;

  

    private string m_sInClearText = "";

    private string m_sCryptedText = "";