Sistem Kriptografi Hybrid (Hill Cipher Dan Knapsack) Pada Pengmanan File
LISTING PROGRAM
1. Form Menu Utama
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using hybrid.Controller; namespace KriptografiHybrid.Controller
{
public partial class mainForm : Form
{
#region
VAR ############
private Boolean bIsExit = false ; #endregion #region KONSTRUKTOR ################### public mainForm()
{ InitializeComponent(); }
#endregion #region PROPERTIES public Boolean isExit
{
get { return bIsExit; }
}
#endregion private void enkripsiToolStripMenuItem_Click( object sender, EventArgs
e) {
encryptForm oForm2 = new encryptForm ();
oForm2.ShowDialog();
if (oForm2.IsAccessible)
{
this .Close();
} }
private void dekripsiToolStripMenuItem_Click( object sender, EventArgs
e) {
decryptForm oForm3 = new decryptForm ();
oForm3.ShowDialog();
if (oForm3.IsAccessible)
{
this .Close();
} } private void exitToolStripMenuItem_Click( object sender, EventArgs
e) { bIsExit = true ;
this .Close();
}
private void bantuanToolStripMenuItem_Click( object sender, EventArgs
e) { }
private void tentangProgrammerToolStripMenuItem_Click( object
sender, EventArgs
e) {
programmerForm oForm4 = new programmerForm ();
oForm4.ShowDialog(); }
private void menggunakanAplikasiToolStripMenuItem_Click( object
sender, EventArgs
e) {
HelpForm oForm5 = new HelpForm ();
oForm5.ShowDialog(); } } }
2. Form Enkripsi
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using hybrid.Lib; using System.Diagnostics; namespace KriptografiHybrid.Controller
{
public partial class encryptForm : Form
{
long jum; int nckey; int n = 0; long [] nil_w = new long [1000]; int [,] tempval = new int [4, 4]; int a; int [,] kunci = new int [4, 4]; private String fileExt; DoubleMatrix k = null ;
#region
VAR ############
// private Boolean bIsExit = false; // private Boolean pembangkitKunciValid = false; #endregion #region KONSTRUKTOR ################### public encryptForm()
{ InitializeComponent(); }
#endregion #region SUDAH DIRAPIKAN /// <summary> /// Set default /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void encryptForm_Load( object sender, EventArgs
e) { cbMatrixKunci.SelectedIndex = 0; }
/// <summary> /// Cari file yang akan di enkripsi /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
private void btnPilihSumberFile_Click( object sender, EventArgs
e) {
OpenFileDialog FileDialog = new OpenFileDialog (); if (FileDialog.ShowDialog() == DialogResult .OK)
{ txtSumberFile.Text = FileDialog.FileName.ToString(); fileExt =
Path .GetExtension(FileDialog.FileName).Substring(1);
txtExtensiSumberFile.Text = fileExt; } }
/// <summary> /// Generate matrix kunci /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnGenerateKunci_Click( object sender, EventArgs
e) { cbJumlahW.Items.Clear();
if (cbMatrixKunci.Text == "2x2" )
{ a = 2;
for ( int i = 2; i < ((32 / 2) + 1); i++)
{
if (32 % i == 0)
{ cbJumlahW.Items.Add(i.ToString()); } } }
else if (cbMatrixKunci.Text == "3x3" )
{ a = 3;
for ( int i = 2; i < ((72 / 2) + 1); i++)
{
if (72 % i == 0)
{ cbJumlahW.Items.Add(i.ToString()); } } }
else if (cbMatrixKunci.Text == "4x4" )
{ a = 4;
for ( int i = 2; i < ((128 / 2) + 1); i++)
{
if (128 % i == 0)
{ cbJumlahW.Items.Add(i.ToString()); } } }
else
{
MessageBox .Show( "Secara Otomatis 2x2" );
a = 2;
for ( int i = 2; i < 17; i++)
{
if (32 % i == 0)
cbJumlahW.Items.Add(i.ToString()); } }
Random rand = new Random (); int b = rand.Next(1, 256);
richTextBox1.Text = "" ;
bool kondisi = false ; while (!kondisi)
{
for ( int i = 0; i < a; i++)
{
for ( int j = 0; j < a; j++)
{ kunci[i, j] = rand.Next(0, 255);
//richTextBox1.Text += kunci[i,j].ToString() + " ";
} richTextBox1.Text += "\n" ; }
int det = 0; if (a == 2)
{ det = (kunci[0, 0] * kunci[1, 1]) - (kunci[1, 0] * kunci[0, 1]);
// MessageBox.Show("hasi determinanan" + det);
}
else if (a == 3)
{ det = ((kunci[0, 0] * kunci[1, 1] * kunci[2, 2]) + (kunci[0, 1] * kunci[1, 2] * kunci[2, 0]) + (kunci[0, 2] * kunci[1, 0] * kunci[2, 1])) - ((kunci[2, 0] * kunci[1, 1] * kunci[0, 2]) + (kunci[2, 1] * kunci[1, 2] * kunci[0, 0]) + (kunci[2, 2] * kunci[1, 0] * kunci[0, 1])); }
else if (a == 4)
{ det = ( ((kunci[0, 0] * kunci[1, 1]) - (kunci[0, 1] * kunci[1, 0])) * ((kunci[2, 2] * kunci[3, 3]) - (kunci[3, 2] * kunci[2, 3])) - ((kunci[2, 0] * kunci[3, 1]) - (kunci[3, 0] * kunci[2, 1])) * ((kunci[0, 2] * kunci[1, 3]) - (kunci[1, 2] * kunci[0, 3])) ); }
while (det < 0)
{ det += 256; }
if (det % 2 != 0)
{
while (((256 * b) + 1) % det == 0)
{ b = rand.Next(1, 256); } richTextBox1.Text = "" ;
for ( int i = 0; i < a; i++)
{
for ( int j = 0; j < a; j++)
{ richTextBox1.Text += kunci[i, j].ToString() + "
" ;
} richTextBox1.Text += "\n" ; } detInv.Text = b.ToString(); kondisi = true ; } }
// Knoversi dari array kunci ke class DoubleMatrix // (nilai byte = 1 {2x2},2{3x3},3{4x4}) int selectedIndexKeyMatrix = cbMatrixKunci.SelectedIndex + 1; if (selectedIndexKeyMatrix == 1) // 2x2
{ k = new DoubleMatrix (2, 2);
// baris dan kolom pada DoubleMatrix terbalik
// baris 0k[0, 0] = kunci[0, 0]; k[1, 0] = kunci[0, 1];
// baris 1
k[0, 1] = kunci[1, 0]; k[1, 1] = kunci[1, 1];
}
else if (selectedIndexKeyMatrix == 2) // 3x3
{ k = new DoubleMatrix (3, 3);
// baris 0
k[0, 0] = kunci[0, 0]; k[1, 0] = kunci[0, 1]; k[2, 0] = kunci[0, 2];
// baris 1
k[0, 1] = kunci[1, 0]; k[1, 1] = kunci[1, 1]; k[2, 1] = kunci[1, 2];
// baris 2
k[0, 2] = kunci[2, 0]; k[1, 2] = kunci[2, 1]; k[2, 2] = kunci[2, 2]; }
else if (selectedIndexKeyMatrix == 3) // 4x4
{ k = new DoubleMatrix (4, 4);
// baris 0
k[0, 0] = kunci[0, 0]; k[1, 0] = kunci[0, 1]; k[2, 0] = kunci[0, 2]; k[3, 0] = kunci[0, 3];
// baris 1
k[0, 1] = kunci[1, 0]; k[1, 1] = kunci[1, 1]; k[2, 1] = kunci[1, 2]; k[3, 1] = kunci[1, 3];
// baris 2
k[0, 2] = kunci[2, 0]; k[1, 2] = kunci[2, 1]; k[2, 2] = kunci[2, 2]; k[3, 2] = kunci[2, 3];
// baris 3
k[0, 3] = kunci[3, 0]; k[1, 3] = kunci[3, 1]; k[2, 3] = kunci[3, 2]; k[3, 3] = kunci[3, 3]; }
Console .WriteLine(k);
}
/// <summary> /// Ambil tujuan file enkripsi /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
private void btnPilihTujuanFile_Click( object sender, EventArgs
e) {
SaveFileDialog saveDialog = new SaveFileDialog ();
saveDialog.DefaultExt = fileExt; saveDialog.AddExtension = true ; saveDialog.Filter = fileExt + + " (*." + fileExt + ")|" fileExt;
if (saveDialog.ShowDialog() == DialogResult .OK)
{ txtTujuanFile.Text = saveDialog.FileName.ToString(); } }
/// <summary> /// Lakukan enkripsi cipher hill /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnEnkripsi_Click( object sender, EventArgs
reader.close(); writer.close(); stopwatch.Stop();
textBox3.Text = fileTerenkrip.getFileSize() + " byte
//ukuran cipherfile FileBitReader fileTerenkrip = new FileBitReader (txtTujuanFile.Text);
textBox6.Text = fileAsli.getFileSize() + " byte " .ToString(); fileAsli.close();
" .ToString(); //ukuran file FileBitReader fileAsli = new FileBitReader (txtSumberFile.Text);
textBox4.Text = stopwatch.ElapsedMilliseconds + " ms
//lama enkripsi
txtTujuanFile.Text + ")" );
MessageBox .Show( "Enkripsi File Berhasil! (" +
HillCipher .encrypt(reader, writer, k); this .timer1.Start();
e) {
writer.writeByte(selectedIndexKey);
// 3. Simpan ukuran key matrix cipher hill (nilai byte = 1 {2x2},2{3x3},3{4x4})
int selectedIndexKey = cbMatrixKunci.SelectedIndex + 1;
writer.writeByte(byteFileSize1); writer.writeByte(byteFileSize2); writer.writeByte(byteFileSize3); writer.writeByte(byteFileSize4);
// 2. Simpan ukuran file int fileSize = ( int )reader.getFileSize(); int byteFileSize1 = fileSize >> 24; int byteFileSize2 = (fileSize >> 16) % 256; int byteFileSize3 = (fileSize >> 8) % 256; int byteFileSize4 = fileSize % 256;
writer.writeByte( "HANNA" );
//DateTime awal, akhir; //awal = DateTime.Now; FileBitReader reader = new FileBitReader (txtSumberFile.Text); FileBitWriter writer = new FileBitWriter (txtTujuanFile.Text); // 1. Simpan pengenal personal
stopwatch.Start();
Stopwatch stopwatch = new Stopwatch ();
" .ToString(); fileTerenkrip.close();
//}
}
/// <summary> /// Pilih jumlah w /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cbJumlahW_SelectedIndexChanged( object sender,
EventArgs
e) {
//int bitnil = 0; if (cbMatrixKunci.Text == "2x2" )
{
// bitnil = 32;
}
else if (cbMatrixKunci.Text == "3x3" )
{
// bitnil = 72;
}
else if (cbMatrixKunci.Text == "4x4" )
{
// bitnil = 128;
}
//else
}
// bitnil = 32; // } /// <summary> /// Bangkitkan w,q,r /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnGenerate_Click( object sender, EventArgs
e) {
if (cbJumlahW.Text == "" )
{
MessageBox .Show( "piih terlebih dahulu banyak item w" );
}
else
{
Random rand = new Random (); long temp = 0;
n = Convert .ToInt32(cbJumlahW.Text); nil_w[0] = 1; jum = nil_w[0]; txtW.Text = nil_w[0].ToString();
for ( int i = 1; i < n; i++)
{
for ( int j = 0; j < i; j++)
{ temp += nil_w[j]; } nil_w[i] = temp + 1; jum += nil_w[i]; txtW.Text += " " + nil_w[i].ToString(); temp = 0;
} {
Random bil = new Random (); int acak = bil.Next(1, 256);
txtQ.Text = (acak + jum).ToString(); } {
Random bil = new Random (); int acak = bil.Next(1, 255);
long Q = Convert .ToInt64(txtQ.Text);
while ( GCD .GCD1(acak, Q) != 1){ acak = bil.Next(1, 255); } txtR.Text = acak.ToString(); } {
long r = Convert .ToInt32(txtR.Text), q = Convert .ToInt64(txtQ.Text);
n = Convert .ToInt32(cbJumlahW.Text);
long [] nilpublic = new long [n];
txtKunciPublik.Text = "" ;
for ( int i = 0; i < n; i++)
{ nilpublic[i] = ((nil_w[i] * r) % q); txtKunciPublik.Text += nilpublic[i].ToString() + "
" ;
} } { txtKunciPrivate.Text = txtW.Text; } }
// dr sini
}
/// <summary> /// Pilih tujuan key disimpan /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
private void btnPilihTujuanKey_Click( object sender, EventArgs
e) {
SaveFileDialog saveDialog = new SaveFileDialog ();
saveDialog.DefaultExt = "cipherkey" ; saveDialog.AddExtension = true ; saveDialog.Filter = "cipherkey (*.cipherkey)|cipherkey" ;
if (saveDialog.ShowDialog() == DialogResult .OK)
{ txtTujuanKey.Text = saveDialog.FileName.ToString(); } }
/// <summary> /// Lakukan enkripsi pada key (Knapsack) /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
private void btn_EnkripsiKunci_Click( object sender, EventArgs
e)
{
Stopwatch stopwatch = new Stopwatch ();
stopwatch.Start();
String cipher = Knapsack .encrypt(n, txtKunciPublik.Text, a,
kunci, nckey, txtTujuanKey.Text, txtQ.Text, txtR.Text, cbJumlahW.Text, txtKunciPrivate.Text); textBox1.Text = cipher; stopwatch.Stop();
MessageBox .Show( "Enkripsi Key Berhasil! (" + txtTujuanKey + ")
- " );
textBox5.Text = stopwatch.ElapsedMilliseconds + " ms
" .ToString();
}
/// <summary> /// Keluar dari form enkripsi /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnBatal_Click( object sender, EventArgs
e) { Close(); }
#region fungsi pembantu public int bin2int( string bin)
{
int num = 0, count = 0; for ( int i = (bin.Length - 1); i >= 0; i--)
{
if (bin[i] == '1' )
num += pangkat(2, count); count++; }
return num;
}
public int pangkat( int
a, int
b) {
int hasil = 1; for ( int i = 1; i <= b; i++)
{ hasil *= a; }
return hasil;
}
public Int64 bruteModulo( Int64
a, Int64
b, Int64
c) {
return (((a % c) * (b % c)) % c);
}
#endregion private void timer1_Tick( object sender, EventArgs
e) {
this .progressBar1.Increment(1);
}
#endregion
} }
3. Form Dekripsi
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using hybrid.Lib; using System.Diagnostics; namespace KriptografiHybrid.Controller
{
public partial class decryptForm : Form
{
// long jum; //int n = 0; long [] nil_w = new long [1000]; int [,] tempval = new int [4, 4]; //int a; int [,] kunci = new int [4, 4]; private String fileExt;
// DoubleMatrix k = null; #region
VAR ############
// private Boolean bIsExit = false; #endregion #region KONSTRUKTOR ################### public decryptForm()
{ InitializeComponent(); }
#endregion #region Sudah Dirapikan /// <summary>
/// Pilih file cipher key dan baca w,q,r,cipherkey ke textbox
/// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnPilihFileCipherKey_Click( object sender, EventArgse) {
OpenFileDialog openKey = new OpenFileDialog ();
openKey.Filter = "cipherkey(*.cipherkey)|*.cipherkey" ;
if (openKey.ShowDialog() == DialogResult .OK)
{
string read = "" ; StreamReader objReader = new StreamReader (openKey.FileName);
txtFileCipherKey.Text = openKey.FileName; read = objReader.ReadLine();
int count = 0; while (read != null )
{
if (count == 0)
{ txt_Q.Text = read; }
else if (count == 1)
{ txt_R.Text = read; }
else if (count == 3)
{ txt_KunciPrivat.Text = read; }
else if (count == 4)
{ txtCipherKey.Text = read; } count++; read = objReader.ReadLine(); } objReader.Close(); } }
/// <summary> /// Lakukan dekripsi knapsack terhadap cipherkey, q, w, r /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_DekripsiCipherkey_Click( object sender, EventArgs
e) {
try
{
Stopwatch stopwatch = new Stopwatch ();
stopwatch.Start();
String result = Knapsack .decrypt(txt_KunciPrivat.Text,
txtCipherKey.Text, txt_Q.Text, txt_R.Text); txt_CipherMatrix.Text = result; stopwatch.Stop();
MessageBox .Show( "Dekripsi Key Berhasil! " );
textBox2.Text = stopwatch.ElapsedMilliseconds + " ms
" .ToString();
}
catch ( Exception TerjadiKesalahan)
{
MessageBox .Show( "Error\n" + TerjadiKesalahan.ToString());
} }
/// <summary> /// Pilih sumber file yang sudah terenkripsi /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
private void btnPilihSumberFile_Click( object sender, EventArgs
e) {
OpenFileDialog FileDialog = new OpenFileDialog (); if (FileDialog.ShowDialog() == DialogResult .OK)
{ txtSumberFileDekripsi.Text = FileDialog.FileName.ToString(); fileExt =
Path .GetExtension(FileDialog.FileName).Substring(1);
} }
/// <summary> /// Pilih dimana file hasil dekripsi disimpan (Cipherhill) /// </summary> /// <param name="sender"></param> /// <param name="e"></param>
private void btnPilihTujuanFile_Click( object sender, EventArgs
e) {
SaveFileDialog saveDialog = new SaveFileDialog ();
saveDialog.DefaultExt = fileExt; saveDialog.AddExtension = true ; saveDialog.Filter = fileExt + " (*." + fileExt + ")|" +fileExt;
if (saveDialog.ShowDialog() == DialogResult .OK)
{ txtTujuanFileDekripsi.Text = saveDialog.FileName.ToString(); } }
/// <summary> /// Lakukan proses dekripsi dan simpan file hasil dekripsi /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Dekripsi_Click( object sender, EventArgs
e) {
Stopwatch stopwatch = new Stopwatch ();
stopwatch.Start();
String key = txt_CipherMatrix.Text; // 45 34 54 23 45 23 45 23 //buang spasi terakhir
key = key.Substring(0, key.Length - 1); // posisi terakhir
adalah spasi String [] keyArr = key.Split( ' ' ); if (keyArr.Length == 4 || keyArr.Length == 9 || keyArr.Length
== 16) {
int jenisMatrix = ( int ) Math .Sqrt(keyArr.Length);
DoubleMatrix k = new DoubleMatrix (jenisMatrix,
jenisMatrix);
int keyArrReaded = 0; for ( int baris = 0; baris < jenisMatrix; baris++)
{
for ( int kolom = 0; kolom < jenisMatrix; kolom++)
{ k[kolom, baris] =
Convert .ToDouble(keyArr[keyArrReaded]);
keyArrReaded++; }
}
Console .WriteLine( "k = " + k); FileBitReader reader = new FileBitReader (txtSumberFileDekripsi.Text); FileBitWriter writer = new FileBitWriter (txtTujuanFileDekripsi.Text); String identifier = String .Empty; for ( int i = 0; i < 5; i++)
{ identifier += ( char )reader.readByte(); }
if (identifier != "HANNA" )
{
MessageBox .Show( "File yang anda pilih, tidak bisa di dekripsi!" );
}
else
{
//(nilai byte = 1 {2x2},2{3x3},3{4x4})
int byteFileSize1 = reader.readByte();
int byteFileSize2 = reader.readByte();
int byteFileSize3 = reader.readByte();
int byteFileSize4 = reader.readByte();
byteFileSize1 = byteFileSize1 << 24; byteFileSize2 = byteFileSize2 << 16; byteFileSize3 = byteFileSize3 << 8;
long ukuranFile = byteFileSize1 + byteFileSize2 +
byteFileSize3 + byteFileSize4; jenisMatrix = reader.readByte();
if (jenisMatrix + 1 != k.RowCount)
{
throw new Exception ( "Jenis matrix tidak cocok!" );
}
HillCipher .decrypt(reader, writer, k, ukuranFile);
stopwatch.Stop();
MessageBox .Show( "Dekripsi File Berhasil! " +
txtTujuanFileDekripsi.Text + ")" );
//lama dekripsi
textBox1.Text = stopwatch.ElapsedMilliseconds + " ms
" .ToString();
}
//MessageBox.Show(identifier);
writer.close(); reader.close(); }
else
{
MessageBox .Show( "Key yang anda masukkan salah! Key harus berupa 2x2; 3x3; 4x4" );
} }
#region Fungsi pembantu public string int2bin( int num, int jum)
{
string bin = "" ; for ( int i = 0; i < jum; i++)
{ if (num % 2 == 1)
{ bin = "1" + bin; }
else
{ bin = "0" + bin; } num = num / 2; }
return bin;
}
#endregion private void btnBatal_Click( object sender, EventArgs
e) { Close(); }
#endregion private void groupBox1_Enter( object sender, EventArgs
e) { } } }
4. Form Menggunakan Aplikasi using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace hybrid.Controller
{
public partial class HelpForm : Form
{
public HelpForm()
{ InitializeComponent(); } } }
5. Form Tentang using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace hybrid.Controller
{
public partial class programmerForm : Form
{
public programmerForm()
{ InitializeComponent(); }
private void programmerForm_Load( object sender, EventArgs
e) { } } }
6. Class Hill Cipher
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace hybrid.Lib
{
class HillCipher
{
public static void encrypt( FileBitReader reader, FileBitWriter
writer, DoubleMatrix k) {
// ambil jenis matrix int jenisMatrix; // total baris = total kolom
jenisMatrix = k.RowCount;
// ambil ukuran file long fileSize = reader.getFileSize(); // variabel count jumlah byte yang sudah dibaca long readedByte = 0; // lakukan pembacaan sampai seluruh file terbaca while (readedByte < fileSize) {
// ambil sebanyak jumlah matrix dan ciptakan matrix DoubleMatrix matrixP = new DoubleMatrix (1, jenisMatrix); int readedP = 0; while (readedP < jenisMatrix)
{
if (readedByte < fileSize)
{ matrixP[0, readedP] = reader.readByte(); readedByte++; }
else
{ matrixP[0, readedP] = 0; } readedP++;
}
DoubleMatrix matrixC = new DoubleMatrix (1, jenisMatrix);
matrixC = k * matrixP; matrixC.mod(256);
//Console.WriteLine("matrixC setelah mod = " + matrixC); for ( int baris = 0; baris < matrixC.RowCount; baris++ )
{ writer.writeByte(( int ) matrixC[0, baris]); } } }
public static void decrypt( FileBitReader reader, FileBitWriter
writer, DoubleMatrix k, long oriFileSize) {
DoubleMatrix adjK = k.adjoint(); double detK = k.determinant(); double x = 0; for ( int i = 1; i < 10000; i++)
{
double hasilModulo = (detK * i) % 256; if (hasilModulo == 1 || (hasilModulo + 256) == 1)
{ x = i;
break ;
}
//if (((256 * i) + 1) % detK == 0 ) { // x = ((256 * i) + 1) / detK; //}
}
if (x == 0) { throw new Exception ( "Tidak bisa menemukan nilai invers Det K" );
}
DoubleMatrix invK = (x * adjK);
invK.mod(256);
for ( int baris = 0; baris < invK.RowCount; baris++ )
{
for ( int kol = 0; kol < invK.ColumnCount; kol++)
{
if (invK[kol, baris] < 0) {
invK[kol, baris] += 256; } } }
// pembuktian DoubleMatrix bukti = k * invK;
bukti.mod(256);
for ( int baris = 0; baris < invK.RowCount; baris++)
{
for ( int kol = 0; kol < invK.ColumnCount; kol++)
{
if (baris == kol)
{
if (bukti[kol, baris] != 1) { throw new Exception ( "Inverse matrix benar!" );
} }
else
{
if (bukti[kol, baris] != 0) {
throw new Exception ( "Inverse matrix salah!" );} } } }
long readedByte = 0; long writtenByte = 0; int jenisMatrix = k.RowCount; //Console.WriteLine("jenisMatrix = " + jenisMatrix); //Console.WriteLine("fileSize = " + fileSize); // lakukan pembacaan sampai seluruh file terbaca while (readedByte < oriFileSize)
{
// ambil sebanyak jumlah matrix dan ciptakan matrix DoubleMatrix matrixC = new DoubleMatrix (1, jenisMatrix); int readedP = 0; while (readedP < jenisMatrix)
{ matrixC[0, readedP] = reader.readByte(); readedByte++; readedP++; }
//Debug.WriteLine("matrixC = " + matrixC); //Console.WriteLine("matrixP = " + matrixP); DoubleMatrix matrixP = new DoubleMatrix (1, jenisMatrix);
matrixP = invK * matrixC;
//Console.WriteLine("matrixC sebelum mod = " + matrixC);
matrixP.mod(256);
//Debug.WriteLine("matrixP = " + matrixP); //Console.WriteLine("matrixC setelah mod = " + matrixC); for ( int baris = 0; baris < matrixP.RowCount; baris++)
{
if (writtenByte < oriFileSize)
{ writer.writeByte(( int )matrixP[0, baris]); writtenByte++; } } } } } }
7. Class Knapsack
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace hybrid.Lib
{
class Knapsack
{
public static String encrypt( int jlhW, string KunciPub, int
jnsMatrix, int [,] kunci, int nckey, String txtTujuanKey , String txtQ, String txtR, String cbJumlahW, String txtKunciPrivate) {
String temp = String .Empty; string kTempPub = "" ; int indeks = 0; int [] kPublic = new int [jlhW]; for ( int i = 0; i < KunciPub.Length; i++)
{
if (KunciPub.ElementAt(i) >= '0' && KunciPub.ElementAt(i)
<= '9' ) { kTempPub += KunciPub.ElementAt(i); }
else
{
if (kTempPub != "" )
{ kPublic[indeks] = Convert .ToInt32(kTempPub); indeks++; kTempPub = "" ; }
else
{ } } }
//int to Biner
temp = "" ;
for ( int i = 0; i < jnsMatrix; i++)
{
for ( int j = 0; j < jnsMatrix; j++)
{ temp += Knapsack .int2bin(kunci[i, j], 8); } }
//MessageBox.Show(temp.Text); //Pisah Menjadi Blok Biner
indeks = 0; kTempPub = "" ; nckey = (temp.Length / jlhW);
int counter = 0; string [] sesiKeyCipher = new string [nckey]; //MessageBox.Show(temp.Text+" "+temp.TextLength); for ( int i = 0; i < temp.Length; i++)
{ counter++;
if (counter == jlhW)
{ kTempPub += temp.ElementAt(i); sesiKeyCipher[indeks] = kTempPub; kTempPub = "" ; indeks++; counter = 0; }
else
{ kTempPub += temp.ElementAt(i); } }
//Perkalian Blok Cipher int [] KeyCipher = new int [nckey];
temp = "" ;
for ( int i = 0; i < nckey; i++)
{ KeyCipher[i] = 0;
for ( int j = 0; j < jlhW; j++)
{
if (sesiKeyCipher[i].ElementAt(j) == '1' )
KeyCipher[i] += kPublic[j]; } temp += KeyCipher[i].ToString() + " " ; }
// Simpan // @TODO!!! try
{
FileStream teks = new FileStream (txtTujuanKey,
FileMode .CreateNew, FileAccess .Write);StreamWriter tulis = new StreamWriter (teks);
tulis.WriteLine(txtQ); tulis.WriteLine(txtR); tulis.WriteLine(cbJumlahW); tulis.WriteLine(txtKunciPrivate); tulis.WriteLine(temp); tulis.Write(nckey.ToString()); tulis.Close(); teks.Close(); }
catch { } return temp;
}
public static string int2bin( int num, int jum)
{
string bin = "" ; for ( int i = 0; i < jum; i++)
{
if (num % 2 == 1)
{ bin = "1" + bin; }
else
{ bin = "0" + bin; } num = num / 2; }
return bin;
} public static int bin2int( string bin)
{
int num = 0, count = 0; for ( int i = (bin.Length - 1); i >= 0; i--)
{
if (bin[i] == '1' )
num += Knapsack .pangkat(2, count); count++; }
return num;
}
public static int pangkat( int
a, int
b) {
int hasil = 1; for ( int i = 1; i <= b; i++)
{ hasil *= a; }
return hasil;
}
public static Int64 bruteModulo( Int64
a, Int64
b, Int64
c) {
return (((a % c) * (b % c)) % c);
}
public static String decrypt( String KunciPri, String cipher, String
txt_Q, String txt_R) {
String txt_CipherMatrix; int nckey = 0; String temp = String .Empty; int n = 0; string kTempPub; //string KunciPub; int indeks = 0; int [] kPublic = new int [n];
indeks = 0; kTempPub = "" ;
int counter = 0; string [] sesiKeyCipher = new string [100]; int [] KeyCipher = new int [100];
temp = "" ;
int [] kPrivate = new int [100];
counter = indeks = 0; kTempPub = "" ;
for ( int i = 0; i < KunciPri.Length; i++)
{
if (KunciPri.ElementAt(i) >= '0' && KunciPri.ElementAt(i)
<= '9' ) { kTempPub += KunciPri.ElementAt(i); }
else
{ if (kTempPub != "" )
{ kPrivate[indeks] = Convert .ToInt32(kTempPub); indeks++; kTempPub = "" ; n++; }
else
{ } }
if (i == KunciPri.Length - 1)
{
if (kTempPub != "" )
{ kPrivate[indeks] = Convert .ToInt32(kTempPub); indeks++; n++; kTempPub = "" ; }
else
{ } } } indeks = 0; kTempPub = "" ;
for ( int i = 0; i < cipher.Length; i++)
{
if (cipher.ElementAt(i) >= '0' && cipher.ElementAt(i) <= '9' )
{ kTempPub += cipher.ElementAt(i); }
else
{
if (kTempPub != "" )
{ KeyCipher[indeks] = Convert .ToInt32(kTempPub); indeks++; kTempPub = "" ; nckey++; }
else
{ } }
if (i == cipher.Length - 1)
{
if (kTempPub != "" )
{ KeyCipher[indeks] = Convert .ToInt32(kTempPub); indeks++;
// MessageBox.Show(KeyCipher[i].ToString());
kTempPub = "" ; }
else
{ } } } kTempPub = "" ;
for ( int i = 0; i < n; i++)
{ kTempPub += "1" ; }
int kombinasi = ( Knapsack .bin2int(kTempPub) + 1); string [] binKombi = new string [kombinasi]; for ( int i = 0; i < kombinasi; i++)
{ binKombi[i] = int2bin(i, n); }
//Biner Total Hasil Dekripsi Int64 q = Convert .ToInt32(txt_Q), r = Convert .ToInt32(txt_R),
nInv, k = 0;
while ((1 + (q * k)) % r != 0)
k++; nInv = (1 + (q * k)) / r;
int [] hasildekrip = new int [nckey]; //int temp1 = 0; String hasildekripBin;
hasildekripBin = "" ;
int nkey_temp = Convert .ToInt32( Math .Pow(2, n)); string [] dataBit = new string [nkey_temp]; int [] dataDec = new int [nkey_temp]; int n_bit = Convert .ToInt32(n); for ( int i = 0; i < nkey_temp; i++)
{ dataBit[i] = int2bin(i, n_bit); dataDec[i] = 0;
for ( int j = 0; j < n_bit; j++)
{ dataDec[i] += ( Convert .ToInt32(dataBit[i][j].ToString()) * kPrivate[j]);
} }
string hasilbittotal = "" ; for ( int i = 0; i < nckey; i++)
{ hasildekrip[i] = Convert .ToInt32(bruteModulo(KeyCipher[i], nInv, q));
for ( int j = 0; j < nkey_temp; j++)
{
if (hasildekrip[i] == dataDec[j])
{ hasilbittotal += dataBit[j];
break ;
} } }
//MessageBox.Show("Hasil\n" + hasilbittotal); int [] hasil = new int [hasilbittotal.Length / 8];
indeks = counter = 0; txt_CipherMatrix = "" ; kTempPub = "" ;
for ( int i = 0; i < hasilbittotal.Length; i++)
{ counter++;
if (counter == 8)
{ kTempPub += hasilbittotal.ElementAt(i); hasil[indeks] = Knapsack .bin2int(kTempPub); txt_CipherMatrix += hasil[indeks].ToString() + " " ; kTempPub = "" ; indeks++; counter = 0; }
else
{ kTempPub += hasilbittotal.ElementAt(i); } }
return txt_CipherMatrix;
} } }
8. Class Baca File
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace hybrid.Lib
{
class FileBitReader
{
private String fileName; private FileStream fileIn; private BufferedStream buffFileIn; public FileBitReader( String fileName)
{
this .fileName = fileName;
fileIn = new FileStream ( this .fileName, FileMode .Open); buffFileIn = new BufferedStream (fileIn); }
public int readByte()
{
return buffFileIn.ReadByte();
}
public long getFileSize()
{ return buffFileIn.Length;
}
public void close()
{ buffFileIn.Close(); fileIn.Close(); } } }
9. Class Tulis File
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace hybrid.Lib
{
class FileBitWriter
{
private String fileName; private FileStream fileOut; private BufferedStream buffFileOut; public FileBitWriter( String fileName)
{
this .fileName = fileName;
fileOut = new FileStream ( this .fileName, FileMode .Create); buffFileOut = new BufferedStream (fileOut); }
public void writeByte( String str)
{
for ( int i = 0; i < str.Length; i++)
{
char karakter = str[i]; byte toWrite = ( byte ) karakter;
buffFileOut.WriteByte(toWrite); } }
public void writeByte( byte
b) { buffFileOut.WriteByte(b); }
public void writeByte( int i)
{ buffFileOut.WriteByte(( byte ) i); }
public void close()
{ buffFileOut.Close(); fileOut.Close(); }
} }
10. Class Double Matrix
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace hybrid.Lib
{
public class DoubleMatrix
{
public double determinant() { if ( this .ColumnCount != this .RowCount)
{
throw new Exception ( "Determinan berlaku pada matrix NxN" );
}
if ( this .ColumnCount == 1)
{
return this [0, 0];
}
if ( this .ColumnCount != 2)
{
throw new NotImplementedException ( "Fungsi hanya bisa melakukan determinant n=2" );
}
int n = this .RowCount; if (n == 2) { //(kunci[0, 0] * kunci[1, 1]) - (kunci[1, 0] * kunci[0, 1]); return ( this [0, 0] * this [1, 1]) - ( this [0, 1] * this [1,
0]); }
public DoubleMatrix adjoint()
{
if ( this .ColumnCount != this .RowCount)
{
throw new Exception ( "Adjoint berlaku pada matrix NxN" );
}
DoubleMatrix cofactor = new DoubleMatrix ( this .ColumnCount, this .RowCount);
for ( int baris = 0; baris < this .RowCount; baris++ )
{
for ( int kolom = 0; kolom < this .ColumnCount; kolom++ )
{
// ambil matrix yang sisa DoubleMatrix matrixSisa = new DoubleMatrix ( this .ColumnCount - 1, this .RowCount-1); int traceBaris = 0; int traceKolom = 0; for ( int loopBaris = 0; loopBaris < this .RowCount;
loopBaris++) { for ( int loopKolom = 0; loopKolom < this .ColumnCount; loopKolom++) { if (baris == loopBaris || kolom == loopKolom) { continue ;
} matrixSisa[traceKolom, traceBaris] =
this [loopKolom, loopBaris];
traceKolom++;
if (traceKolom >= matrixSisa.ColumnCount) {
traceKolom = 0; traceBaris++; } } } cofactor[kolom, baris] = Math .Pow(-1, baris + kolom) * matrixSisa.determinant();
} }
return cofactor.Transposed;
}
public void mod( int mod)
{
for ( int baris = 0; baris < this .RowCount; baris++)
{
for ( int kol = 0; kol < this .ColumnCount; kol++)
{
this [kol, baris] = this [kol, baris] % mod;
} } } } }
11. Class GCD
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace hybrid.Lib
{
class GCD
{
public static long GCD1( long
a, long
b) {
while (b != 0)
{
long tmp = b;
b = a % b; a = tmp; }
return a;
} } }
89 Y 133 À 177
▒ 221 ¦
68 D 112 p 156 £ 200 ╚ 244 (
59 ; 103 g 147 Ô 191 ┐ 235 δ 16 ►
60 < 104 h 148 Ö 192 └ 236 ∞
17 ◄ 61 = 105 i 149 Ò 193 ┴
237 φ 18 ↕ 62 > 106 j 150 Û 194 ┬
238 ε 19 ‼ 63 ? 107 k 151 Ù 195 ├
239 ∩ 20 ¶
64 @ 108 l 152 Ÿ 196 ─ 240 ≡
21 §
65 A 109 m 153 Ö 197 ┼ 241 ±
22 ▬
66 B 110 n 154 Ü 198 ã 242 ≥
23 ↨
67 C 111 o 155 ¢ 199 Ã 243 ≤
24 ↑
25 ↓
57 9 101 e 145 Æ 189 ¢ 233 Θ 14 ♫
69 E 113 q 157 ¥ 201 ╔ 245 ) 26 →
70 F 114 r 158 P 202 ╩ 246 ÷ 27 ←
71 G 115 s 159 Ƒ 203 ╦
247 ≈ 28 ∟
72 H 116 t 160 Á 204 ╠ 248 °
29 ↔
73 I 117 u 161 Í 205 ═ 249 ·
30 ▲
74 J 118 v 162 Ó 206 ╬ 250 ·
31 ▼
75 K 119 w 163 Ú 207 ¤ 251
√32
76 L 120 x 164 Ñ 208 ð 252 n
33 !
58 : 102 f 146 Æ 190 ¥ 234
Ω 15 ☼13
TABEL ASCII No Kode No Kode No Kode No Kode No Kode No Kode
2
94 ^ 138 È 182
 226 Γ44 ,
88 X 132 Ä 176 ░ 220 ▄
1 ☺
45
2 ☻ 46 .
90 Z 134 Å 178
▓ 222 Ì3 ♥ 47 /
91 [ 135 Ç 179
│ 223 ▀4 ♦ 48
92 \ 136 Ê 180
┤224 α 5 ♣
49
1 93 ] 137 Ë 181 Á 225 ß
6 ♠
50
7
56 8 100 d 144 É 188 ╝ 232 Φ