Tuesday, January 3, 2017

Kriptosistem Simetris Menggunakan C#.NET (Bagian 1)


Kriptosistem Simetris dan Integritas Data
Menggunakan C#.NET (Bagian 1)






1.1 Kriptosistem RC4






using System;
using System.Globalization;
using System.Text;
using System.Collections;


namespace KriptoRC4
{
        public class MesinRC4
        {
                #region Konstruktor

                public MesinRC4()
                {
                }

                #endregion

                #region Metode Publik

                public bool Enkripsi()
                {
                        bool toRet = true;

                        try
                        {
                                //
                                // indeks yang akan digunakan
                                //
                                long i=0;
                                long j=0;

                                //
                                // Menempatkan string masukan ke dalam array byte temporer
                                //
                                Encoding pengkodeanDefault = Encoding.Default;
                                byte[] masukan  =
                                        pengkodeanDefault.GetBytes(this.m_sPlainteks);
                               
                                //
                                // Menghasilkan array byte
                                //
                                byte[] keluaran = new byte[masukan.Length];
                               
                                //
                                // Salinan lokal dari m_nPjgKotak
                                //
                                byte[] n_LokalKotak = new byte[m_nPjgKotak];
                                this.m_nKotak.CopyTo(n_LokalKotak,0);
                               
                                //
                                //      Panjang dari Chipher
                                //
                                long PanjangCipher = masukan.Length + 1;

                                //
                                // Menjalankan algoritma
                                //
                                for ( long offset = 0; offset < masukan.Length ; offset++ )
                                {
                                        i = ( i + 1 ) % m_nPjgKotak;
                                        j = ( j + n_LokalKotak[i] ) %  m_nPjgKotak;
                                        byte temp =  n_LokalKotak[i];
                                        n_LokalKotak[i] = n_LokalKotak[j];
                                        n_LokalKotak[j] = temp;
                                        byte a = masukan[offset];
                                        byte b =
                                                n_LokalKotak[(n_LokalKotak[i]+n_LokalKotak[j])%
                                                m_nPjgKotak];
                                        keluaran[offset] = (byte)((int)a^(int)b);      
                                }      
                               
                                //
                                // Menempatkan hasil ke dalam string keluaran
                                //
                                char[] keluaranArrChar = new char[pengkodeanDefault.GetCharCount(keluaran,0,keluaran.Length)];
                                pengkodeanDefault.GetChars(keluaran,0,keluaran.Length,keluaranArrChar,0);
                                this.m_sTeksEnkripsi = new string (keluaranArrChar);
                        }
                        catch
                        {
                                toRet = false;
                        }

                        return ( toRet );

                }

                public bool Dekripsi()
                {
                        bool toRet = true;

                        try
                        {
                                this.m_sPlainteks = this.m_sTeksEnkripsi;
                                m_sTeksEnkripsi = "";
                                if (toRet = Enkripsi())
                                {
                                        m_sPlainteks = m_sTeksEnkripsi;
                                }
                       
                        }
                        catch
                        {
                                toRet = false;
                        }
                       
                        return toRet;
                }
               
                #endregion

                #region Definisi-Definisi

                public string KunciEnkripsi
                {
                        get
                        {
                                return ( this.m_sKunciEnkripsi );
                        }
                        set
                        {
                                //
                                // menugaskan nilai hanya ketika ia nilai baru
                                //
                                if ( this.m_sKunciEnkripsi != value )
                                {      
                                        this.m_sKunciEnkripsi = value;

                                        //
                                        // Digunakan untuk mengisi m_nKotak
                                        //
                                        long indeks2 = 0;

                                        //
                                        // Menciptakan dua pengkodean yang berbeda
                                        //
                                        Encoding asciiPengkodean                = Encoding.ASCII;
                                        Encoding unicodePengkodean          = Encoding.Unicode;

                                        //
                                        // Melakukan konvesi kunci enkripsi dari unicode menjadi ansi
                                        //
                                        byte[] asciiByte =
  Encoding.Convert(unicodePengkodean,asciiPengkodean,unicodePengkodean.GetBytes(this.m_sKunciEnkripsi));

                                        //
                                        // Mengkonversi byte[] menjadi char[] dan kemudian menjadi string
                                        //
                                       
                                        char[] asciiKarakter = new char[asciiPengkodean.GetCharCount(asciiByte,0,asciiByte.Length)];
                                        asciiPengkodean.GetChars(asciiByte,0,asciiByte.Length,asciiKarakter,0);
                                        this.m_sKunciEnkripsiAscii = new string(asciiKarakter);

                                        //
                                        // Mengisi m_nKotak
                                        //
                                        long PjgKunci = m_sKunciEnkripsi.Length;
                                       
                                        //
                                        // Loop pertama
                                        //
                                        for ( long hitung = 0; hitung < m_nPjgKotak ; hitung ++ )
                                        {
                                                this.m_nKotak[hitung] = (byte)hitung;
                                        }
                                       
                                        //
                                        // Loop kedua
                                        //
                                        for ( long hitung = 0; hitung < m_nPjgKotak ; hitung ++ )
                                        {
                                                indeks2 = (indeks2 + m_nKotak[hitung] +
                                                        asciiKarakter[ hitung % PjgKunci ]) %
                                                        m_nPjgKotak;
                                                byte temp               = m_nKotak[hitung];
                                                m_nKotak[hitung]        = m_nKotak[indeks2];
                                                m_nKotak[indeks2]       = temp;
                                        }

                                }
                        }
                }

                public string PlainTeks
                {
                        get
                        {
                                return ( this.m_sPlainteks );
                        }
                        set
                        {
                                //
                                        // menugaskan nilai hanya jika ia nilai baru
                                //
                                if (this.m_sPlainteks   != value)
                                {      
                                        this.m_sPlainteks       = value;
                                }
                        }
                }

                public string TeksTerenkripsi
                {
                        get
                        {
                                return ( this.m_sTeksEnkripsi );
                        }
                        set
                        {
                                //
                                // menugaskan nilai hanya jika ia nilai baru
                                //
                                if ( this.m_sTeksEnkripsi != value )
                                {      
                                        this.m_sTeksEnkripsi = value;
                                }
                        }
                }
                #endregion

                #region Bidang-Bidang Privat
               
                //
                // Kunci enkripsi: versi unicode dan ascii
                //
                private string m_sKunciEnkripsi         = "";
                private string m_sKunciEnkripsiAscii = "";
                //
                // Berkaitan dengan kunci enkripsi
                //
                protected byte[] m_nKotak = new byte[m_nPjgKotak];
                //
                // Panjang dari nKotak
                //
                static public long m_nPjgKotak = 255;
               
                private string m_sPlainteks     = "";
                private string m_sTeksEnkripsi  = "";
               
                #endregion

        }
}

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace KriptoRC4
{

        public class FormKriptoRC4 : System.Windows.Forms.Form
        {
                private System.Windows.Forms.TextBox teksMasukan;
                private System.Windows.Forms.TextBox teksKeluaran;
                private System.Windows.Forms.Button btnEnkripsi;
                private System.Windows.Forms.Button btnDekripsi;
                private System.Windows.Forms.Label lblKotakMasukan;
                private System.Windows.Forms.Label lblKotakKeluaran;
                private System.Windows.Forms.Label lblKunci;
                private System.Windows.Forms.TextBox teksKunciEnkripsi;
                private System.Windows.Forms.Label lblPeringatan;
                private System.Windows.Forms.Label lblMaksimum;

                private System.ComponentModel.Container iKontainer = null;

                public FormKriptoRC4()
                {
                        InitializeComponent();
                }

                protected override void Dispose( bool disposing )
                {
                        if( disposing )
                        {
                                if (iKontainer != null)
                                {
                                        iKontainer.Dispose();
                                }
                        }
                        base.Dispose( disposing );
                }

                [STAThread]
                static void Main()
                {
                        Application.Run(new FormKriptoRC4());
                }

                #region Fungsi-fungsi kontrol user

        private void FormKriptoRC4_Load(object sender, System.EventArgs e)
                {
                        this.btnDekripsi.Visible = false;
                        this.btnEnkripsi.Visible = false;

                        this.lblMaksimum.Text = "Maks " + this.teksMasukan.MaxLength + " Karakter";
                }

        private void teksKunciEnkripsi_LostFocus(object sender, System.EventArgs e)
                {
                        if ( this.teksKunciEnkripsi.Text.ToString() == "" )
                        {
                                MessageBox.Show ("Kunci enkripsi tidak bisa NULL!","Error");
                        }
                }


                private void teksMasukan_TextChanged(object sender, System.EventArgs e)
                {
                        if ( this.teksMasukan.Text.ToString() != "" )
                        {
                                if ( !this.btnEnkripsi.Visible )
                                {
                                        this.btnEnkripsi.Visible = true;
                                }
                        }
                        else
                        {
                                if ( this.btnEnkripsi.Visible )
                                {
                                        this.btnEnkripsi.Visible = false;
                                }
                        }
                }

                private void teksKeluaran_TextChanged(object sender, System.EventArgs e)
                {
                        if ( this.teksKeluaran.Text.ToString() != "" )
                        {
                                if ( !this.btnDekripsi.Visible )
                                {
                                        this.btnDekripsi.Visible = true;
                                }

                                this.m_sSimpanKripto = this.teksKeluaran.Text;
                        }
                        else
                        {
                                if ( this.btnDekripsi.Visible )
                                {
                                        this.btnDekripsi.Visible = false;
                                }
                        }
                }

        private void btnEnkripsi_Click(object sender, System.EventArgs e)
                {
                        if ( this.teksKeluaran.Text.ToString() != "" )
                        {
                                MessageBox.Show ("Kotak teks enkripsi akan dihapus!","Pesan peringatan");
                                this.teksKeluaran.Text = "";
                        }
                       
                        MesinRC4 kuMesinRC4                 = new MesinRC4();
                        kuMesinRC4.KunciEnkripsi        = this.teksKunciEnkripsi.Text;
                        kuMesinRC4.PlainTeks            = this.teksMasukan.Text;
                        kuMesinRC4.Enkripsi();

                        this.m_sSimpanKripto                    = kuMesinRC4.TeksTerenkripsi;
                        this.teksKeluaran.Text          = this.m_sSimpanKripto;
                }

                private void btnDekripsi_Click(object sender, System.EventArgs e)
                {
                        if ( this.teksMasukan.Text.ToString() != "" )
                        {
                                MessageBox.Show ("Kotak plainteks akan dihapus!", "Pesan peringatan");
                                this.teksMasukan.Text = "";
                        }

                        MesinRC4 kuMesinRC4                 = new MesinRC4();
                        kuMesinRC4.KunciEnkripsi        = this.teksKunciEnkripsi.Text;
                        kuMesinRC4.TeksTerenkripsi      = this.m_sSimpanKripto;
                        kuMesinRC4.Dekripsi();
                        this.teksMasukan.Text           = kuMesinRC4.PlainTeks;
                }
                #endregion

                #region Bidang private user
                private string m_sSimpanKripto = "";
                #endregion

        }
}



1.2 Kriptosistem DES







using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;

namespace KriptosistemDES
{
    public partial class FormDES : Form
    {
        public FormDES()
        {

            InitializeComponent();
        }
       
        DESCryptoServiceProvider kunci = new DESCryptoServiceProvider();
        byte[] buffer;

        public static byte[] Enkripsi(string strTeks, SymmetricAlgorithm kunci)
        {
            // Menciptakan aliran memori.
            MemoryStream aliranMemori = new MemoryStream();

            // Menciptakan sebuaha CryptoStream menggunakan aliran memori dan
            // kunci DES. 
            CryptoStream aliranKripto = new CryptoStream(aliranMemori, kunci.CreateEncryptor(),
                CryptoStreamMode.Write);

            // Menciptakan sebuah StreamWriter untuk menuliskan sebuah string
            // pada aliran.
            StreamWriter sw = new StreamWriter(aliranKripto);

            // Menuliskan strTeks pada aliran.
            sw.WriteLine(strTeks);

            // Menutup StreamWriter dan CryptoStream.
            sw.Close();
            aliranKripto.Close();

            // Mendapatkan sebuah array byte yagng merepresentasikan aliran memori.
            byte[] buffer = aliranMemori.ToArray();

            // Menutup aliran memori.
            aliranMemori.Close();

            // Menghasilkan array byte terenksripsi.
            return buffer;
        }


        public static string Dekripsi(byte[] teksTerenkripsi, SymmetricAlgorithm kunci)
        {
            // Menciptakan sebuah aliran memori untuk buffer yang dilewatkan.
            MemoryStream aliranMemori = new MemoryStream(teksTerenkripsi);

            // Menciptakan sebuaha CryptoStream menggunakan aliran memori dan
            // kunci DES.
            CryptoStream aliranKripto = new CryptoStream(aliranMemori, kunci.CreateDecryptor(),
                CryptoStreamMode.Read);

            // Menciptakan sebuah StreamReader untuk membaca aliran.
            StreamReader sr = new StreamReader(aliranKripto);

            // Membaca aliran sebagai sebuah string.
            string val = sr.ReadLine();

            // Menutup aliran-aliran.
            sr.Close();
            aliranKripto.Close();
            aliranMemori.Close();

            return val;
        }
        private void btnEnkripsi_Click(object sender, EventArgs e)
        {
            buffer = Enkripsi(teksPlain.Text, kunci);
            foreach (byte b in buffer)
            {
                teksTerenkripsi.AppendText(b.ToString());
            }
        }

        private void btnDekripsi_Click(object sender, EventArgs e)
        {
            if (teksPlain.Text == string.Empty || teksTerenkripsi.Text == string.Empty)
            {
                MessageBox.Show("Masukkan teks terenkripsi lebih dahulu");
            }
            else
            {
                string strText = Dekripsi(buffer, kunci);
                teksTerdekripsi.Text = strText;
            }
           
        }
    }
}



1.3 Kriptosistem TripleDES





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;

namespace KriptosistemTipleDES
{
    public partial class FormTripleDES : Form
    {
        public FormTripleDES()
        {

            InitializeComponent();
        }
       
        // Menciptakan kunci triple des
        TripleDESCryptoServiceProvider kunci = new TripleDESCryptoServiceProvider();
        byte[] buffer;

        public static byte[] Enkripsi(string strTeks, SymmetricAlgorithm kunci)
        {
            // Menciptakan aliran memori.
            MemoryStream aliranMemori = new MemoryStream();

            // Menciptakan sebuaha CryptoStream menggunakan aliran memori dan
            // kunci TripleDES. 
            CryptoStream aliranKripto = new CryptoStream(aliranMemori, kunci.CreateEncryptor(),
                CryptoStreamMode.Write);

            // Menciptakan sebuah StreamWriter untuk menuliskan sebuah string
            // pada aliran.
            StreamWriter sw = new StreamWriter(aliranKripto);

            // Menuliskan strTeks pada aliran.
            sw.WriteLine(strTeks);

            // Menutup StreamWriter dan CryptoStream.
            sw.Close();
            aliranKripto.Close();

            // Mendapatkan sebuah array byte yagng merepresentasikan aliran memori.
            byte[] buffer = aliranMemori.ToArray();

            // Menutup aliran memori.
            aliranMemori.Close();

            // Menghasilkan array byte terenksripsi.
            return buffer;
        }


        public static string Dekripsi(byte[] teksTerenkripsi, SymmetricAlgorithm kunci)
        {
            // Menciptakan sebuah aliran memori untuk buffer yang dilewatkan.
            MemoryStream aliranMemori = new MemoryStream(teksTerenkripsi);

            // Menciptakan sebuaha CryptoStream menggunakan aliran memori dan
            // kunci TripleDES.
            CryptoStream aliranKripto = new CryptoStream(aliranMemori, kunci.CreateDecryptor(),
                CryptoStreamMode.Read);

            // Menciptakan sebuah StreamReader untuk membaca aliran.
            StreamReader sr = new StreamReader(aliranKripto);

            // Membaca aliran sebagai sebuah string.
            string val = sr.ReadLine();

            // Menutup aliran-aliran.
            sr.Close();
            aliranKripto.Close();
            aliranMemori.Close();

            return val;
        }
        private void btnEnkripsi_Click(object sender, EventArgs e)
        {
            buffer = Enkripsi(teksPlain.Text, kunci);
            foreach (byte b in buffer)
            {
                teksTerenkripsi.AppendText(b.ToString());
            }
        }

        private void btnDekripsi_Click(object sender, EventArgs e)
        {
            if (teksPlain.Text == string.Empty || teksTerenkripsi.Text == string.Empty)
            {
                MessageBox.Show("Masukkan teks terenkripsi lebih dahulu");
            }
            else
            {
                string strText = Dekripsi(buffer, kunci);
                teksTerdekripsi.Text = strText;
            }
           
        }
    }
}




1.4 Kriptosistem Rijndael




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;

namespace KriptoRijndael
{
    public partial class FormRijndael : Form
    {
        public FormRijndael()
        {
            InitializeComponent();
        }

        public static string Enkripsi(string Teks, byte[] kunci, byte[] VektorByte)
        {
            try
            {

                byte[] TeksByte = Encoding.UTF8.GetBytes(Teks);
                RijndaelManaged rijKunci = new RijndaelManaged();
                rijKunci.Mode = CipherMode.CBC;           
                ICryptoTransform enkriptor = rijKunci.CreateEncryptor(kunci,VektorByte);               
                MemoryStream aliranMemori = new MemoryStream();            
                CryptoStream aliranKripto = new
                        CryptoStream(aliranMemori,enkriptor,CryptoStreamMode.Write);              
                aliranKripto.Write(TeksByte, 0, TeksByte.Length);              
                aliranKripto.FlushFinalBlock();              
                byte[] cipherTeksByte = aliranMemori.ToArray();
                aliranMemori.Close();
                aliranKripto.Close();               
                string cipherTeks = Convert.ToBase64String(cipherTeksByte);               
                return cipherTeks;
            }           
            catch (Exception e)
            {
                MessageBox.Show("Password salah "+ e.Message.ToString());
                string t = "";
                return t;
            }
        }

        public static string Dekripsi(string Teks, byte[] kunciByte, byte[] VektorByte)
        {
            try
            {
                byte[] TeksByte = Convert.FromBase64String(Teks);               
                RijndaelManaged rijKunci = new RijndaelManaged();
                rijKunci.Mode = CipherMode.CBC;
                ICryptoTransform dekriptor = rijKunci.CreateDecryptor(kunciByte,VektorByte);
                MemoryStream aliranMemori = new MemoryStream(TeksByte);
                CryptoStream aliranKripto = new
                        CryptoStream(aliranMemori,dekriptor,CryptoStreamMode.Read);
                byte[] pTeksByte = new byte[TeksByte.Length];
                int terdekripsiByteKounter = aliranKripto.Read(pTeksByte,0,pTeksByte.Length);
                aliranMemori.Close();
                aliranKripto.Close();
                string plainTeks = Encoding.UTF8.GetString(pTeksByte,0,terdekripsiByteKounter);
                return plainTeks;
            }
            catch (Exception a)
            {
                MessageBox.Show("Password salah "+ a.Message.ToString());
                string t = "";
                return t;
            }
        }


        private void btnEnkripsi_Click(object sender, EventArgs e)
        {

            byte[] salt = { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] V = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            PasswordDeriveBytes cdk = new PasswordDeriveBytes(teksPassword.Text,salt);
            //string kex = Convert.ToBase64String(cdk.CryptDeriveKey("RC2", "SHA1", 128, salt));
            byte[] kunciByte = cdk.CryptDeriveKey("RC2", "SHA1", 128, salt);
                string answer = Enkripsi(teksPlainteks.Text, kunciByte,V);
                teksTerenkripsi.Text = answer;

        }

        private void btnDekripsi_Click(object sender, EventArgs e)
        {
            byte[] salt = { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] V = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            PasswordDeriveBytes cdk = new PasswordDeriveBytes(teksPassword.Text, salt);
            //string kex = Convert.ToBase64String(cdk.CryptDeriveKey("RC2", "SHA1", 128, salt));
            byte[] kunciByte = cdk.CryptDeriveKey("RC2", "SHA1", 128, salt);
                string answer = Dekripsi(teksTerenkripsi.Text, kunciByte, V);
                teksPlainteks.Text = answer;

            }
    }
}



1.5 Kriptosistem Rijndael Untuk Enkripsi File




using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace EnkripsiDekripsi
{
    public class EnkriptorKu
    {
        // Nilai internal dari fase dipakai untuk membangkitkan kunci rahasia
        private string _Frase = "";
        // Memuat path file masukan dan namanya
        private string _fileMasukan = "";
        // Memuat path file masukan dan namanya
        private string _fileKeluaran = "";
        enum TipeTransformasi { ENKRIPSI = 0, DEKRIPSI = 1 } 
      
        public string Frase
        {
            set
            {
                this._Frase = value;
                this.BangkitkanKunci(this._Frase);
            }
        }      

        private byte[] _IV;

        // nilai kunci rahasia internal
        private byte[] _Kunci;

        public EnkriptorKu(string FraseRahasia)
        {
            this.Frase = FraseRahasia;
        }

        public string Enkripsi(string NilaiEnkripsi)
        {
            try
            {
                if (NilaiEnkripsi.Length > 0)
                {                 
                    // Menuliskan nilai terenkripsi ke dalam memori
                    byte[] masukan = Encoding.UTF8.GetBytes(NilaiEnkripsi);             
                   
                    // Membaca nilai terenkripsi
                    return
                (Convert.ToBase64String(Transformasi(masukan,TipeTransformasi.ENKRIPSI)));
                   
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }           
        }

        public string Dekripsi(string NilaiDekripsi)
        {        
           
            try
            {
                if (NilaiDekripsi.Length > 0)
                {                 
                    // Menuliskan nilai terdekripsi ke dalam memori                   
                    byte[] masukan = Convert.FromBase64String(NilaiDekripsi);               

                    // Membaca nilai terdekripsi
                    return
                (Encoding.UTF8.GetString(Transformasi(masukan,TipeTransformasi.DEKRIPSI)));

                }
                else
                {
                    return "";
                }
            }           
            catch (Exception ex)
            {
                throw ex;
            }          
        }

        public void Enkripsi(string FileMasukan, string FileKeluaran)
        {     

            try
            {
                if ((FileMasukan != null) && (FileMasukan.Length > 0))
                {
                    _fileMasukan = FileMasukan;
                }
                if ((FileKeluaran != null) && (FileKeluaran.Length > 0))
                {
                    _fileKeluaran = FileKeluaran;
                }
                Transformasi(null, TipeTransformasi.ENKRIPSI);
            }
            catch (Exception ex)
            {
                throw ex;
            }           
        }

        public void Dekripsi(string FileMasukan, string FileKeluaran)
        {

            try
            {
                if ((FileMasukan != null) && (FileMasukan.Length > 0))
                {
                    _fileMasukan = FileMasukan;
                }
                if ((FileKeluaran != null) && (FileKeluaran.Length > 0))
                {
                    _fileKeluaran = FileKeluaran;
                }
                Transformasi(null, TipeTransformasi.DEKRIPSI);
            }
            catch (Exception ex)
            {
                throw ex;
            }           
        }

        private void BangkitkanKunci(string FraseRahasia)
        {
            this._Kunci = new byte[24];
            this._IV = new byte[16];

            byte[] byteFrase = Encoding.ASCII.GetBytes(FraseRahasia);
            SHA384Managed sha384 = new SHA384Managed();
            sha384.ComputeHash(byteFrase);
            byte[] hasil = sha384.Hash;

            for (int loop = 0; loop < 24; loop++) this._Kunci[loop] = hasil[loop];
            for (int loop = 24; loop < 40; loop++) this._IV[loop - 24] = hasil[loop];
        }

        private byte[] Transformasi(byte[] masukan, TipeTransformasi tipeTransformasi)
        {
            CryptoStream aliranKripto = null;     
            RijndaelManaged rijndael = null;       
            ICryptoTransform rijndaelTransformasi = null;          
            FileStream fsMasukan = null;                
            FileStream fsKeluaran = null;               
            MemoryStream aliranMemori = null;         
            try
            {
                rijndael = new RijndaelManaged();
                rijndael.Key = this._Kunci;
                rijndael.IV = this._IV;
                if (tipeTransformasi == TipeTransformasi.ENKRIPSI)
                {
                    rijndaelTransformasi = rijndael.CreateEncryptor();
                }
                else
                {
                    rijndaelTransformasi = rijndael.CreateDecryptor();
                }

                if ((masukan != null) && (masukan.Length > 0))
                {
                    aliranMemori = new MemoryStream();
                    aliranKripto = new CryptoStream(
                         aliranMemori, rijndaelTransformasi, CryptoStreamMode.Write);

                    aliranKripto.Write(masukan, 0, masukan.Length);

                    aliranKripto.FlushFinalBlock();

                    return aliranMemori.ToArray();

                }
                else if ((_fileMasukan.Length > 0) && (_fileKeluaran.Length > 0))
                {
                    fsMasukan = new FileStream(_fileMasukan,
                                FileMode.Open, FileAccess.Read);
                    fsKeluaran = new FileStream(_fileKeluaran,
                                FileMode.OpenOrCreate, FileAccess.Write);

                    aliranKripto = new CryptoStream(
                        fsKeluaran, rijndaelTransformasi, CryptoStreamMode.Write);

                    int bufferPjg = 4096;
                    byte[] buffer = new byte[bufferPjg];
                    int byteDibaca;
                    do
                    {
                        byteDibaca = fsMasukan.Read(buffer, 0, bufferPjg);
                        aliranKripto.Write(buffer, 0, byteDibaca);

                    } while (byteDibaca != 0);

                    aliranKripto.FlushFinalBlock();                   
                }              
                    return null;          
               
            }
            catch (CryptographicException)
            {
                throw new CryptographicException("Password tak valid. Silahkan verifikasi ulang.");
            }
            finally
            {
                if (rijndael != null) rijndael.Clear();
                if (rijndaelTransformasi != null) rijndaelTransformasi.Dispose();
                if (aliranKripto != null) aliranKripto.Close();
                if (aliranMemori != null) aliranMemori.Close();
                if (fsKeluaran != null) fsKeluaran.Close();
                if (fsMasukan != null) fsMasukan.Close();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace KriptoRijndaelFILE
{
    public partial class FormKriptoRijndaelFILE : Form
    {       
        public FormKriptoRijndaelFILE()
        {
            InitializeComponent();
        }

        private void btnEnkripsi_Click(object sender, EventArgs e)
        {
            try
            {               
                EnkripsiDekripsi.EnkriptorKu enc = new
                        EnkripsiDekripsi.EnkriptorKu(txtPhrase.Text.Trim());
                teksTerenkripsi.Text = enc.Enkripsi(teksPlainteks.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDekripsi_Click(object sender, EventArgs e)
        {
            try
            {
                EnkripsiDekripsi.EnkriptorKu enc = new
                        EnkripsiDekripsi.EnkriptorKu(txtPhrase.Text.Trim());
                teksPlainteks.Text = enc.Dekripsi(teksTerenkripsi.Text.Trim());
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnBrowseDekripsi_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";
            openFileDialog1.Title = "Pilih file untuk didekripsi";
            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.Filter = "File-file enkripsi (*.enkripsi) | *.enkripsi";

            string strFileDidekripsi = "";            
            string strKeluaranDekripsi = "";

            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                strFileDidekripsi = openFileDialog1.FileName;              
                teksFileDidekripsi.Text = strFileDidekripsi;
                int iPosisi;               

                iPosisi = strFileDidekripsi.LastIndexOf(".enkripsi");
                if((iPosisi == -1) || (iPosisi != (strFileDidekripsi.Length-9)))
                {
                    MessageBox.Show("File tak valid. Pilih file terenkripsi yang tepat.");
                }

                strKeluaranDekripsi = strFileDidekripsi.Substring(0, strFileDidekripsi.Length - 8);                      

                iPosisi = strKeluaranDekripsi.IndexOf("z_z");
                if (iPosisi == -1)
                {
                    strKeluaranDekripsi = strKeluaranDekripsi + ".dat";
                }
                else
                {
                    strKeluaranDekripsi = strKeluaranDekripsi.Replace("z_z", ".");
                }
                teksFileDestinasiDekripsi.Text = strKeluaranDekripsi;
                btnDekripsiFile.Enabled = true;           
            }
        }

        private void btnBrowseEnkripsi_Click(object sender, EventArgs e)
        {
            openFileDialog1.FileName = "";
            openFileDialog1.Title = "Pilih file untuk dienkripsi";
            openFileDialog1.InitialDirectory = @"C:\";

            string strFileDienkripsi = "";
            string strKeluaranEnkripsi = "";
            string strEkstensi = "";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                strFileDienkripsi = openFileDialog1.FileName;
                teksFileDiEnkripsi.Text = strFileDienkripsi;
                int iPosisi;              

                iPosisi = strFileDienkripsi.LastIndexOf(".");
                if (iPosisi == -1)
                {
                    MessageBox.Show("File tak valid. Silahkan pilih file yang tepat.");
                }

                strEkstensi = strFileDienkripsi.Substring(iPosisi, (strFileDienkripsi.Length - iPosisi));

                string strEkstensiTerenkripsi = "z_z" + strEkstensi.Substring(1) + ".enkripsi";        
                strKeluaranEnkripsi = strFileDienkripsi.Replace(strEkstensi,
                        strEkstensiTerenkripsi);

                teksFileDestinasiEnkripsi.Text = strKeluaranEnkripsi;
                btnEnkripsiFile.Enabled = true;
            }
        }

        private void btnDekripsiFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (teksPasswodUlangDekripsi.Text != teksPasswordDekripsi.Text)
                {
                    teksPasswodUlangDekripsi.Text = "";
                    MessageBox.Show("Password tidak sama, silahkan verifikasi kembali.");
                    return;
                }
                string strKunciRahasia = teksPasswordDekripsi.Text.Trim();
                EnkripsiDekripsi.EnkriptorKu enk = new
                        EnkripsiDekripsi.EnkriptorKu(strKunciRahasia);
                enk.Dekripsi(teksFileDidekripsi.Text, teksFileDestinasiDekripsi.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnEnkripsiFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (teksPasswordUlangEnkripsi.Text != teksPasswordEnkripsi.Text)
                {
                    teksPasswordUlangEnkripsi.Text = "";
                    MessageBox.Show("Password tidak sama, silahkan verifikasi kembali.");
                    return;
                }
                string strKunciRahasia = teksPasswordEnkripsi.Text.Trim();
                EnkripsiDekripsi.EnkriptorKu enk = new
                        EnkripsiDekripsi.EnkriptorKu(strKunciRahasia);
                enk.Enkripsi(teksFileDiEnkripsi.Text, teksFileDestinasiEnkripsi.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
      
    }
}


  
1.6 Kriptosistem RC2/DES/Rijndael






using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace KriptoRC2DESRijndael
{
    class MesinKripto
    {
        static RC2CryptoServiceProvider rc2CSP;
        static DESCryptoServiceProvider desProvider;
        static MesinKripto()
        {
            rc2CSP = new RC2CryptoServiceProvider();
            desProvider = new DESCryptoServiceProvider();
        }

        #region RijndaelManaged

        public static string RijndaelManagedEnkripsi(string plainTeks)
        {
            byte[] teks = Encoding.ASCII.GetBytes(plainTeks);

            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            byte[] salt = Encoding.ASCII.GetBytes("kunci kriptoku".Length.ToString());

            PasswordDeriveBytes KunciRahasia = new PasswordDeriveBytes("kunci kriptoku", salt);

            ICryptoTransform Enkriptor =
                RijndaelCipher.CreateEncryptor(KunciRahasia.GetBytes(32),
                KunciRahasia.GetBytes(16));
            MemoryStream aliranMemori = new MemoryStream();

            CryptoStream aliranKripto = new CryptoStream(aliranMemori, Enkriptor,
                CryptoStreamMode.Write);
            aliranKripto.Write(teks, 0, teks.Length);

            aliranKripto.FlushFinalBlock();

            byte[] CipherByte = aliranMemori.ToArray();

            aliranMemori.Close();
            aliranKripto.Close();

            return Convert.ToBase64String(CipherByte);
        }

        public static string RijndaelManagedDekripsi(string plainTeks)
        {
            byte[] teks = Convert.FromBase64String(plainTeks);

            RijndaelManaged RijndaelCipher = new RijndaelManaged();
            byte[] salt = Encoding.ASCII.GetBytes("kunci kriptoku".Length.ToString());

            PasswordDeriveBytes KunciRahasia = new PasswordDeriveBytes("kunci kriptoku", salt);

            ICryptoTransform dekriptor =
                RijndaelCipher.CreateDecryptor(KunciRahasia.GetBytes(32),
                KunciRahasia.GetBytes(16));
            MemoryStream aliranMemori = new MemoryStream(teks);

            CryptoStream aliranKripto = new CryptoStream(aliranMemori, dekriptor,
                CryptoStreamMode.Read);
            teks = new byte[teks.Length];
            int TerdekripsiHitung = aliranKripto.Read(teks, 0, teks.Length);

            aliranMemori.Close();
            aliranKripto.Close();
            return Encoding.ASCII.GetString(teks);
        }
        #endregion

        #region RC2Provider

        public static string RC2ProviderEnkripsi(string plainTeks)
        {
            byte[] teks = Encoding.ASCII.GetBytes(plainTeks);

            // Mendapatkan kunci dan IV.
            byte[] kunci = rc2CSP.Key;
            byte[] IV = rc2CSP.IV;

            // Mendapatkan enkriptor.
            ICryptoTransform enkriptor = rc2CSP.CreateEncryptor(kunci, IV);
            byte[] terEnkripsi = GenerikEnkriptor(teks, enkriptor);

            // Mengkonversi array byte menjadi sebuah string.
            return Convert.ToBase64String(terEnkripsi);
        }

        private static byte[] GenerikEnkriptor(byte[] teks, ICryptoTransform enkriptor)
        {
            // Mengenkripsi data sebagai sebuah array yang memuat byte-byte terenkripsi pada memori.
            MemoryStream msEnkripsi = new MemoryStream();
            CryptoStream csEnkripsi = new CryptoStream(msEnkripsi, enkriptor,
                CryptoStreamMode.Write);

            // Menuliskan semua data ke dalam aliran kripto.
            csEnkripsi.Write(teks, 0, teks.Length);
            csEnkripsi.FlushFinalBlock();

            // Mendapatkan array byte terenkripsi.
            byte[] encrypted = msEnkripsi.ToArray();
            return encrypted;
        }

        public static string RC2ProviderDekripsi(string plainTeks)
        {
            byte[] teks = Convert.FromBase64String(plainTeks);

            // Mendapatkan kunci dan IV.
            byte[] kunci = rc2CSP.Key;
            byte[] IV = rc2CSP.IV;

            //Mendapatkan dekriptor dan menggunakan kunci dan IV yang sama dengan enkriptor.
            ICryptoTransform dekriptor = rc2CSP.CreateDecryptor(kunci, IV);

            string dekStr = GenerikDekriptor(teks, dekriptor);
            return dekStr;
        }
        #endregion

        #region Enkripsi DES

        public static string DESProviderEnkripsi(string plainTeks)
        {
            byte[] teks = Encoding.ASCII.GetBytes(plainTeks);
           
            ICryptoTransform enkriptor = desProvider.CreateEncryptor();
            byte[] terEnkripsi = GenerikEnkriptor(teks, enkriptor);

            return Convert.ToBase64String(terEnkripsi);
        }

        public static string DESProviderDekripsi(string plainTeks)
        {
            byte[] teks = Convert.FromBase64String(plainTeks);
           
            // Menciptakan sebuah aliran memori.
            MemoryStream ms = new MemoryStream(teks);
            ICryptoTransform dekriptor = desProvider.CreateDecryptor();
           
            string dekStr = GenerikDekriptor(teks, dekriptor);
            return dekStr;
        }
        #endregion

        public static string GenerikDekriptor(byte[] cypher, ICryptoTransform dekriptor)
        {
            MemoryStream msDekripsi = new MemoryStream(cypher);
            CryptoStream csDekripsi = new CryptoStream(msDekripsi, dekriptor,
                CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(csDekripsi, Encoding.ASCII);
            string dekStr = sr.ReadToEnd();

            msDekripsi.Close();
            csDekripsi.Close();
            sr.Close();
            return dekStr;
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace KriptoRC2DESRijndael
{
    public partial class Enkripsi : Form
    {
        public Enkripsi()
        {
            InitializeComponent();
        }

        private void Enkripsi_Load(object sender, EventArgs e)
        {
            cmbAlgoritma.SelectedIndex = 0;
        }

        private void btnHapus_Click(object sender, EventArgs e)
        {
            cmbAlgoritma.SelectedIndex = 0;

            teksPlainteks.Text = string.Empty;
            teksEnkripsi.Text = string.Empty;
            teksDekripsi.Text = string.Empty;           
        }

        private void cmbAlgoritma_SelectedIndexChanged(object sender, EventArgs e)
        {
            teksPlainteks.Text = string.Empty;
            teksEnkripsi.Text = string.Empty;
            teksDekripsi.Text = string.Empty;           
        }

        private void btnEnkripsi_Click(object sender, EventArgs e)
        {
            try
            {
                switch (cmbAlgoritma.SelectedItem.ToString())
                {

                    case "Rijndael Managed":
                        teksEnkripsi.Text =
                                MesinKripto.RijndaelManagedEnkripsi(teksPlainteks.Text);
                        break;
                    case "RC2 Provider":
                        teksEnkripsi.Text = MesinKripto.RC2ProviderEnkripsi(teksPlainteks.Text);
                        break;
                    case "DES Provider":
                        teksEnkripsi.Text = MesinKripto.DESProviderEnkripsi(teksPlainteks.Text);
                        break;
                    case "Triple DES Provider":
                        break;
                    case "MD5 Provider":
                        break;
                    case "SHA 256 Managed":
                        break;
                    case "DSA Provider":
                        break;
                    case "RSA Provider":
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Mesin Kripto");
            }
        }

        private void btnDekripsi_Click(object sender, EventArgs e)
        {
            try
            {
                switch (cmbAlgoritma.SelectedItem.ToString())
                {

                    case "Rijndael Managed":
                        teksDekripsi.Text =
                                MesinKripto.RijndaelManagedDekripsi(teksEnkripsi.Text);
                        break;
                    case "RC2 Provider":
                        teksDekripsi.Text = MesinKripto.RC2ProviderDekripsi(teksEnkripsi.Text);
                        break;
                    case "DES Provider":
                        teksDekripsi.Text = MesinKripto.DESProviderDekripsi(teksEnkripsi.Text);
                        break;
                    case "Triple DES Provider":
                        break;
                    case "MD5 Provider":
                        break;
                    case "SHA 256 Managed":
                        break;
                    case "DSA Provider":
                        break;
                    case "RSA Provider":
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Mesin Kripto");
            }
        }
    }
}


  
1.7 Kriptosistem RC2/DES/Rijndael dengan Password





using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace KriptoRC2DESRijndael
{
    class MesinKripto
    {
        static RC2CryptoServiceProvider rc2CSP;
        static DESCryptoServiceProvider desProvider;
        static MesinKripto()
        {
            rc2CSP = new RC2CryptoServiceProvider();
            desProvider = new DESCryptoServiceProvider();
        }

        #region RijndaelManaged

        public static string RijndaelManagedEnkripsi(string plainTeks, string password)
        {
            byte[] teks = Encoding.ASCII.GetBytes(plainTeks);

            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            byte[] salt = Encoding.ASCII.GetBytes(password.Length.ToString());

            PasswordDeriveBytes KunciRahasia = new PasswordDeriveBytes(password, salt);

            ICryptoTransform Enkriptor =
                RijndaelCipher.CreateEncryptor(KunciRahasia.GetBytes(32),
                KunciRahasia.GetBytes(16));
            MemoryStream aliranMemori = new MemoryStream();

            CryptoStream aliranKripto = new CryptoStream(aliranMemori, Enkriptor,
                CryptoStreamMode.Write);
            aliranKripto.Write(teks, 0, teks.Length);

            aliranKripto.FlushFinalBlock();

            byte[] CipherByte = aliranMemori.ToArray();

            aliranMemori.Close();
            aliranKripto.Close();

            return Convert.ToBase64String(CipherByte);
        }

        public static string RijndaelManagedDekripsi(string plainTeks, string password)
        {
            byte[] teks = Convert.FromBase64String(plainTeks);

            RijndaelManaged RijndaelCipher = new RijndaelManaged();
            byte[] salt = Encoding.ASCII.GetBytes(password.Length.ToString());

            PasswordDeriveBytes KunciRahasia = new PasswordDeriveBytes(password, salt);

            ICryptoTransform dekriptor =
                RijndaelCipher.CreateDecryptor(KunciRahasia.GetBytes(32),
                KunciRahasia.GetBytes(16));
            MemoryStream aliranMemori = new MemoryStream(teks);

            CryptoStream aliranKripto = new CryptoStream(aliranMemori, dekriptor,
                CryptoStreamMode.Read);
            teks = new byte[teks.Length];
            int TerdekripsiHitung = aliranKripto.Read(teks, 0, teks.Length);

            aliranMemori.Close();
            aliranKripto.Close();

            return Encoding.ASCII.GetString(teks);
        }
        #endregion

        #region RC2Provider
        public static string RC2ProviderEnkripsi(string plainTeks, string password)
        {
            byte[] teks = Encoding.ASCII.GetBytes(plainTeks);

            PasswordDeriveBytes cdk = new PasswordDeriveBytes(password, null);

            // Menghasilkan sebuah kunci RC2.
            byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] kunci = cdk.CryptDeriveKey("RC2", "SHA1", 128, iv);

            // Menciptakan objek RC2 untuk mengenkripsi dengan kunci terderivasi
            rc2CSP.Key = kunci;
            rc2CSP.IV = new byte[] { 21, 22, 23, 24, 25, 26, 27, 28 };

            // Mendapatkan enkriptor.
            ICryptoTransform enkriptor = rc2CSP.CreateEncryptor(rc2CSP.Key, rc2CSP.IV);
            byte[] diEnkripsi = GenerikEnkriptor(teks, enkriptor);

            // Mengkonvesi array bte menjadi string kembali.
            return Convert.ToBase64String(diEnkripsi);
        }

        public static byte[] GenerikEnkriptor(byte[] teks, ICryptoTransform enkriptor)
        {

            // Mengenkripsi data sebagai sebuah array byte terenkripsi pada memori.
            MemoryStream msEnkripsi = new MemoryStream();
            CryptoStream csEnkripsi = new CryptoStream(msEnkripsi, enkriptor,
                CryptoStreamMode.Write);

            // Menuliskan data pada aliran kriptor.
            csEnkripsi.Write(teks, 0, teks.Length);
            csEnkripsi.FlushFinalBlock();

            // Mendapatkan array byte terenkripsi.
            byte[] diEnkripsi = msEnkripsi.ToArray();
            return diEnkripsi;
        }

        public static string RC2ProviderDekripsi(string plainTeks, string password)
        {
            byte[] teks = Convert.FromBase64String(plainTeks);

            PasswordDeriveBytes cdk = new PasswordDeriveBytes(password, null);

            // Membangkirkan sebuah kunci RC2
            byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] kunci = cdk.CryptDeriveKey("RC2", "SHA1", 128, iv);

            // Menciptakan objek RC2 untuk mendekripsi dengan kunci terderivasi
            rc2CSP.Key = kunci;
            rc2CSP.IV = new byte[] { 21, 22, 23, 24, 25, 26, 27, 28 };

            //Mendapatkan sebuah dekriptor yang menggunakan kunci dan IV yang sama dengan dekriptor.
            ICryptoTransform decryptor = rc2CSP.CreateDecryptor(rc2CSP.Key, rc2CSP.IV);

            string dekStr = GenerikDekriptor(teks, decryptor);

            return dekStr;
        }
        #endregion

        #region Enkripsi DES
        public static string DESProviderEnkripsi(string plainTeks, string password)
        {
            byte[] teks = Encoding.ASCII.GetBytes(plainTeks);

            PasswordDeriveBytes cdk = new PasswordDeriveBytes(password, null);

            // Membangkitkan kunci DES
            byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] kunci = cdk.CryptDeriveKey("DES", "SHA1", desProvider.KeySize, iv);

            // Menciptakan objek DES untuk mengenkripsi dengan kunci terderivasi
            desProvider.Key = kunci;
            desProvider.IV = new byte[] { 21, 22, 23, 24, 25, 26, 27, 28 };

            ICryptoTransform enkriptor = desProvider.CreateEncryptor(desProvider.Key,
                desProvider.IV);
            byte[] diEnkripsi = GenerikEnkriptor(teks, enkriptor);

            return Convert.ToBase64String(diEnkripsi);
        }

        public static string DESProviderDekripsi(string plainTeks, string password)
        {
            byte[] teks = Convert.FromBase64String(plainTeks);

            PasswordDeriveBytes cdk = new PasswordDeriveBytes(password, null);

            // Membangkirkan sebuah kunci DES
            byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
            byte[] kunci = cdk.CryptDeriveKey("DES", "SHA1", desProvider.KeySize, iv);

            // Menciptakan sebuah objek DES untuk mendekripsi dengan kunci terderivasi
            desProvider.Key = kunci;
            desProvider.IV = new byte[] { 21, 22, 23, 24, 25, 26, 27, 28 };

            // Menciptakan sebuah aliran memori.
            MemoryStream ms = new MemoryStream(teks);
            ICryptoTransform dekriptor = desProvider.CreateDecryptor(desProvider.Key,
                desProvider.IV);

            string dekStr = GenerikDekriptor(teks, dekriptor);

            return dekStr;
        }
        #endregion

        public static string GenerikDekriptor(byte[] cipher, ICryptoTransform dekriptor)
        {
            MemoryStream msDekripsi = new MemoryStream(cipher);
            CryptoStream csDekripsi = new CryptoStream(msDekripsi, dekriptor,
                CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(csDekripsi, Encoding.ASCII);
            string dekStr = sr.ReadToEnd();

            msDekripsi.Close();
            csDekripsi.Close();
            sr.Close();
            return dekStr;
        }

    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace KriptoRC2DESRijndael
{
    public partial class FormEnkripsi : Form
    {
        public FormEnkripsi()
        {
            InitializeComponent();
        }

        private void FormEnkripsi_Load(object sender, EventArgs e)
        {
            cmbAlgoritma.SelectedIndex = 0;
        }

        private void btnHapus_Click(object sender, EventArgs e)
        {
            cmbAlgoritma.SelectedIndex = 0;

            teksPlainteks.Text = string.Empty;
            teksEnkripsi.Text = string.Empty;
            teksDekripsi.Text = string.Empty;           
        }

        private void cmbAlgoritma_SelectedIndexChanged(object sender, EventArgs e)
        {
            teksPlainteks.Text = string.Empty;
            teksEnkripsi.Text = string.Empty;
            teksDekripsi.Text = string.Empty;           
        }

        private void btnEnkripsi_Click(object sender, EventArgs e)
        {
            try
            {
                switch (cmbAlgoritma.SelectedItem.ToString())
                {

                    case "Rijndael Managed":
                        teksEnkripsi.Text =
                        MesinKripto.RijndaelManagedEnkripsi(teksPlainteks.Text,
                                teksPassword.Text);
                        break;
                    case "RC2 Provider":
                        teksEnkripsi.Text = MesinKripto.RC2ProviderEnkripsi(teksPlainteks.Text,
                                teksPassword.Text);
                        break;
                    case "DES Provider":
                        teksEnkripsi.Text = MesinKripto.DESProviderEnkripsi(teksPlainteks.Text,
                                teksPassword.Text);
                        break;
                    case "Triple DES Provider":
                        break;
                    case "MD5 Provider":
                        break;
                    case "SHA 256 Managed":
                        break;
                    case "DSA Provider":
                        break;
                    case "RSA Provider":
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Mesin Kripto");
            }
        }

        private void btnDekripsi_Click(object sender, EventArgs e)
        {
            try
            {
                switch (cmbAlgoritma.SelectedItem.ToString())
                {

                    case "Rijndael Managed":
                        teksDekripsi.Text =
                                MesinKripto.RijndaelManagedDekripsi(teksEnkripsi.Text,
                                teksPassword.Text);
                        break;
                    case "RC2 Provider":
                        teksDekripsi.Text = MesinKripto.RC2ProviderDekripsi(teksEnkripsi.Text,
                                teksPassword.Text);
                        break;
                    case "DES Provider":
                        teksDekripsi.Text = MesinKripto.DESProviderDekripsi(teksEnkripsi.Text,
                                teksPassword.Text);
                        break;
                    case "Triple DES Provider":
                        break;
                    case "MD5 Provider":
                        break;
                    case "SHA 256 Managed":
                        break;
                    case "DSA Provider":
                        break;
                    case "RSA Provider":
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kunci/Password tak valid", "Mesin Kripto");
            }
        }
    }
}



1.8 Kriptosistem TEA




using System;

namespace KriptoTEA
{
        public class Util
        {
                // Konstruktor.
                public Util()
                {
                }
                public static uint KonversiStringKeUInt(string Masukan)
                {
                        uint keluaran;
                        keluaran =  ((uint)Masukan[0]);
                        keluaran += ((uint)Masukan[1] << 8);
                        keluaran += ((uint)Masukan[2] << 16);
                        keluaran += ((uint)Masukan[3] << 24);
                        return keluaran;
                }

                public static string KonversiUIntKeString(uint Masukan)
                {
                        System.Text.StringBuilder output = new System.Text.StringBuilder();
                        output.Append((char)((Masukan & 0xFF)));
                        output.Append((char)((Masukan >> 8) & 0xFF));
                        output.Append((char)((Masukan >> 16) & 0xFF));
                        output.Append((char)((Masukan >> 24) & 0xFF));
                        return output.ToString();
                }
        }
}

using System;

namespace KriptoTEA
{
        public class Tea
        {
                // Konstruktor
                public Tea()
                {
                }

                public string EnkripsiString(string Data, string Kunci)
                {
                        if(Data.Length == 0)
                                throw new ArgumentException("Data sedikitnya harus 1 karakter.");

                        uint[] terformatKunci = FormatKunci(Kunci);

                        if(Data.Length%2!=0) Data += '\0'; // Memastikan array panjang genap.          
                        byte[] dataByteArr = System.Text.ASCIIEncoding.ASCII.GetBytes(Data);

                        string cipher = string.Empty;
                        uint[] tempData = new uint[2];
                        for(int i=0; i<dataByteArr.Length; i+=2)
                        {
                                tempData[0] = dataByteArr[i];
                                tempData[1] = dataByteArr[i+1];
                                kode(tempData, terformatKunci);
                                cipher += Util.KonversiUIntKeString(tempData[0]) +
                                        Util.KonversiUIntKeString(tempData[1]);
                        }
                       
                        return cipher;
                }

                public string Dekripsi(string Data, string Kunci)
                {
                        uint[] terformatKunci = FormatKunci(Kunci);

                        int x = 0;
                        uint[] tempData = new uint[2];
                        byte[] dataByteArr = new byte[Data.Length / 8 * 2];
                        for(int i=0; i<Data.Length; i+=8)
                        {
                                tempData[0] = Util.KonversiStringKeUInt(Data.Substring(i, 4));
                                tempData[1] = Util.KonversiStringKeUInt(Data.Substring(i+4, 4));
                                dekode(tempData, terformatKunci);
                                dataByteArr[x++] = (byte)tempData[0];
                                dataByteArr[x++] = (byte)tempData[1];
                        }

                        string dekripsiString =
                                System.Text.ASCIIEncoding.ASCII.GetString(dataByteArr, 0,
                                dataByteArr.Length);
                        if(dekripsiString[dekripsiString.Length - 1] == '\0')
                                dekripsiString = dekripsiString.Substring(0,
                                        dekripsiString.Length - 1);
                        return dekripsiString;
                }

                public uint[] FormatKunci(string Kunci)
                {
                        if(Kunci.Length == 0)
                                throw new ArgumentException("Kunci harus dengan panjang antara 1 sampai 16 karakter");

                        Kunci = Kunci.PadRight(16,' ').Substring(0, 16); // Memastikan kunci panjang 16 karakter.
                        uint[] terformatKunci = new uint[4];

                        int j = 0;
                        for(int i=0; i<Kunci.Length; i+=4)
                                terformatKunci[j++] =
                                        Util.KonversiStringKeUInt(Kunci.Substring(i, 4));

                        return terformatKunci;
                }

                #region Algoritma TEA
                public void kode(uint[] v, uint[] k) 
                {             
                        uint y = v[0];
                        uint z = v[1];
                        uint jum = 0;  
                        uint delta=0x9e3779b9;
                        uint n=32;            

                        while (n-- > 0)
                        {                      
                                jum += delta;
                                y += (z << 4) + k[0] ^ z + jum ^ (z >> 5) + k[1];
                                z += (y << 4) + k[2] ^ y + jum ^ (y >> 5) + k[3];  
                        }

                        v[0]=y;
                        v[1]=z;
                }

                public void dekode(uint[] v, uint[] k) 
                {
                        uint n=32;
                        uint jum;
                        uint y=v[0];
                        uint z=v[1];
                        uint delta=0x9e3779b9;

                        jum = delta << 5 ;

                        while (n-- > 0)
                        {
                                z -= (y << 4) + k[2] ^ y + jum ^ (y >> 5) + k[3];
                                y -= (z << 4) + k[0] ^ z + jum ^ (z >> 5) + k[1];
                                jum -= delta; 
                        }

                        v[0]=y;
                        v[1]=z;
                }
                #endregion
        }
}

using System;

namespace KriptoTEA
{
        public class XTea
        {
                // Konstruktor
                public XTea()
                {
                }

                public string EnkripsiString(string Data, string Kunci)
                {
                        if(Data.Length == 0)
                                throw new ArgumentException("Data sedikitnya 1 karakter.");

                        uint[] terformatKunci = FormatKunci(Kunci);

                        if(Data.Length%2!=0) Data += '\0';             
                        byte[] dataByteArr = System.Text.ASCIIEncoding.ASCII.GetBytes(Data);

                        string cipher = string.Empty;
                        uint[] tempData = new uint[2];
                        for(int i=0; i<dataByteArr.Length; i+=2)
                        {
                                tempData[0] = dataByteArr[i];
                                tempData[1] = dataByteArr[i+1];
                                kode(tempData, terformatKunci);
                                cipher += Util.KonversiUIntKeString(tempData[0]) +
                                        Util.KonversiUIntKeString(tempData[1]);
                        }
                       
                        return cipher;
                }

                public string Dekripsi(string Data, string Kunci)
                {
                        uint[] terformatKunci = FormatKunci(Kunci);

                        int x = 0;
                        uint[] tempData = new uint[2];
                        byte[] dataByteArr = new byte[Data.Length / 8 * 2];
                        for(int i=0; i<Data.Length; i+=8)
                        {
                                tempData[0] = Util.KonversiStringKeUInt(Data.Substring(i, 4));
                                tempData[1] = Util.KonversiStringKeUInt(Data.Substring(i+4, 4));
                                dekode(tempData, terformatKunci);
                                dataByteArr[x++] = (byte)tempData[0];
                                dataByteArr[x++] = (byte)tempData[1];
                        }
                        string dekripsiString =
                                System.Text.ASCIIEncoding.ASCII.GetString(dataByteArr, 0,
                                dataByteArr.Length);
                        if(dekripsiString[dekripsiString.Length - 1] == '\0')
                                dekripsiString = dekripsiString.Substring(0,
                                        dekripsiString.Length - 1);
                        return dekripsiString;
                }

                public uint[] FormatKunci(string Kunci)
                {
                        if(Kunci.Length == 0)
                                throw new ArgumentException("Panjang kunci harus antara 1 dan 16 karakter");

                        Kunci = Kunci.PadRight(16,' ').Substring(0, 16); // Memastikan panjang kunci 16 karakter.
                        uint[] terformatKunci = new uint[4];

                        int j = 0;
                        for(int i=0; i<Kunci.Length; i+=4)
                                terformatKunci[j++] =
                                        Util.KonversiStringKeUInt(Kunci.Substring(i, 4));

                        return terformatKunci;
                }

                #region Algoritma XTea
                private void kode(uint[] v, uint[] k)
                {
                        uint y = v[0];
                        uint z = v[1];
                        uint jum = 0;
                        uint delta=0x9E3779B9;
                        uint n=32;

                        while(n-->0)
                        {
                                y += (z << 4 ^ z >> 5) + z ^ jum + k[jum & 3];
                                jum += delta;
                                z += (y << 4 ^ y >> 5) + y ^ jum + k[jum >> 11 & 3];
                        }

                        v[0]=y;
                        v[1]=z;
                }

                private void dekode(uint[] v, uint[] k)
                {
                        uint y=v[0];
                        uint z=v[1];
                        uint jum=0xC6EF3720;
                        uint delta=0x9E3779B9;
                        uint n=32;

                        while(n-->0)
                        {
                                z -= (y << 4 ^ y >> 5) + y ^ jum + k[jum >> 11 & 3];
                                jum -= delta;
                                y -= (z << 4 ^ z >> 5) + z ^ jum + k[jum & 3];
                        }
  
                        v[0]=y;
                        v[1]=z;
                }
                #endregion
        }
}



1.9 Kriptosistem XOR




using System;
using System.Collections.Generic;
using System.Text;

namespace MesinKriptoXOR
{
    static class EnkripsiDekripsiXOR
    {
        private static string _b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk.mnopqrstuvwxyz-123456789+/=";

        public static string Enkode(string data, string kunci)
        {
            int kunciPos = 0;
            string binerData = "";

            //Konversi string menjadi data biner 8 bit
            foreach (char c in data)
            {
                int xor = ((int)c ^ (int)kunci[kunciPos]) + (kunci.Length);
                Console.WriteLine("{0} = {1}\t{2} = {3}: {4} = {5}", c, (int)c, kunci[kunciPos],
                        (int)kunci[kunciPos], xor, DecKeBiner(xor, 8));
                if (++kunciPos >= kunci.Length)
                    kunciPos = 0;

                binerData += DecKeBiner(xor, 8);
            }

            int m = 0;
            string cipher = "";
            // memecah string biner menjadi potongan 4byte dan menugaskan kepada setiap potongan nilai b64 yang sesuai
            for (int i = 0; i < binerData.Length; i += 4)
            {
                int v = BinKeDec(binerData.Substring(i, 4));
                cipher += GetB64DariN(v * 4 + m);
                Console.WriteLine("{0}\t{1}\t{2} {3}", v, v * 4 + m, m, GetB64DariN(v * 4 + m)[0]);
                if (++m > 3)
                    m = 0;
            }
            return cipher;
        }

        public static string Dekode(string data, string kunci)
        {
            int m = 0;
            string binerData = "";
            // Konversi string b64 menjadi string biner
            foreach (char c in data)
            {
                int v = (GetNDariB64(c) - m) / 4;
                binerData += DecKeBiner(v, 4);
                Console.WriteLine("{0}", DecKeBiner(v, 4));
                if (++m > 3)
                    m = 0;
            }

            int kunciPos = 0;
            string diDekode = "";
            for (int i = 0; i < binerData.Length; i += 8)
            {
                if (i + 8 > binerData.Length)
                    break;
                int c = BinKeDec(binerData.Substring(i, 8));
                int dc = (c - kunci.Length) ^ (int)kunci[kunciPos];
                Console.WriteLine("{0} = {1}", binerData.Substring(i, 8), c);
                Console.WriteLine("               {0} - {1} ^ {2} = {3}", c, kunci.Length - 1,
                        (int)kunci[kunciPos], (c - kunci.Length) ^ (int)kunci[kunciPos]);

                if (++kunciPos >= kunci.Length)
                    kunciPos = 0;

                diDekode += new string((char)dc, 1);
            }
            return diDekode;
        }

        private static int GetNDariB64(char n)
        {
            return _b64.IndexOf(n);
        }

        private static string GetB64DariN(int n)
        {
            if (n > _b64.Length)
                return "=";

            return new string(_b64[n], 1);
        }

        private static string DecKeBiner(int nilai, int panjang)
        {
            string binString = "";

            while (nilai > 0)
            {
                binString += nilai % 2;
                nilai /= 2;
            }

            string terbalikString = "";
            foreach (char c in binString)
                terbalikString = new string((char)c, 1) + terbalikString;
            binString = terbalikString;

            // pengganjalan
            binString = new string((char)'0', panjang - binString.Length) + binString;

            return binString;
        }

        private static int BinKeDec(string Biner)
        {
            return Convert.ToInt32(Biner, 2);
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MesinKriptoXOR
{
    public partial class FormXOR : Form
    {
        public FormXOR()
        {
            InitializeComponent();
        }

        private void btnEnkripsi_Click(object sender, EventArgs e)
        {
            teksHasil.Text = EnkripsiDekripsiXOR.Enkode(teksStringSumber.Text, teksKunci.Text);
        }

        private void btnDekripsi_Click(object sender, EventArgs e)
        {
            teksHasil.Text = EnkripsiDekripsiXOR.Dekode(teksStringSumber.Text, teksKunci.Text);
        }
    }
}




No comments: