13,247,448 members (88,659 online)
alternative version

#### Stats

229.5K views
53 bookmarked
Posted 4 Apr 2007

# Simple Cryptographer - Simple DES/AES Implementation in C#

, 21 May 2007
 Rate this:
It's very simple and does not focus on performance, but I think that it is simple.

## Introduction

It's a simple DES/AES Encrypt and Decrypt program that uses string data type. If it helps someone who needs to get some practical source code, it'll be my honor.

Caution: I'm not good at writing in English, so be careful if there are some inappropriate sentences. Thank you... hahaha.

## Background

Background? Understanding about C#2.0 and string data type and, of course, Cryptography.

I got so many(???) complaints about tell-you-nothing posts.:)
So I will describe some implementation of The Simple Cryptographer.

But it's too stupid to reinvent the wheel, so I recommend reading some good articles about DES and AES.

I read these articles when I implemented The Simple Cryptographer.

#### How DES Wrks in SimpleCryptographer

First, al the permutation tables in DES and the S-BOXes are declared like this:

```public static readonly int[] pc_1 ={ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50,
42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
27, 19, 11, 3, 60, 52, 44, 36, 63, 55,
47, 39, 31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
13, 5, 28, 20, 12, 4 };
public static readonly int[,] s1 ={ { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9,
0, 7 },
{ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9,
5, 3, 8 },
{ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3,
10, 5, 0 },
{ 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10,
0, 6, 13 } };```

All the other methods in the `ProcessDES `class except `EncryptionStart`, `DecryptionStart`, `DoPermutation`, `SetAllKeys`, `FinalEncription`, `f`, `P`, `sBox_Transform`, `E_Selection `are just helper methods, so just focus on DES-process.

And it starts with making 16-sub keys.

```string hex_key = this.FromTextToHex(key);
string binary_key = this.FromHexToBinary(hex_key);
string key_plus = this.DoPermutation(binary_key, DESData.pc_1);
string C0 = "", D0 = "";
C0 = this.SetLeftHalvesKey(key_plus);
D0 = this.SetRightHalvesKey(key_plus);
Keys keys = this.SetAllKeys(C0, D0);```

The key input is hexa decimal, so convert it to binary decimal for bit permutations and transformations.

And permutate the key by permutation table PC-1, and split this key into left and right halves, `C0 `and `D0`.

And make 16 sub-keys.

```public Keys SetAllKeys(string C0, string D0)
{
Keys keys = new Keys();
keys.Cn[0] = C0;
keys.Dn[0] = D0;
for (int i = 1; i < keys.Cn.Length; i++)
{
keys.Cn[i] = this.LeftShift(keys.Cn[i - 1], DESData.nrOfShifts[i]);
keys.Dn[i] = this.LeftShift(keys.Dn[i - 1], DESData.nrOfShifts[i]);
keys.Kn[i - 1] = this.DoPermutation(keys.Cn[i] + keys.Dn[i],
DESData.pc_2);
}
return keys;
}
```

It's just the implementation of create 16-subkeys in DES.

Please refer to a good explanation in the linked DES article above.

And now, encrypt data block process.

```binaryText = this.setTextMutipleOf64Bits(binaryText);
StringBuilder EncryptedTextBuilder = new StringBuilder(binaryText.Length);
for (int i = 0; i < (binaryText.Length / 64); i++)
{
string PermutatedText = this.DoPermutation(binaryText.Substring(i * 64, 64),
DESData.ip);
string L0 = "", R0 = "";
L0 = this.SetLeftHalvesKey(PermutatedText);
R0 = this.SetRightHalvesKey(PermutatedText);
string FinalText = this.FinalEncription(L0, R0, keys, false);
EncryptedTextBuilder.Append(FinalText);
}```

First, set the total data size to a multiple of 64bit because DES is a block cipher that encrypts 64bit data block at once.

I use `StringBuilder `for reducing string garbage, but I think string is not a good choice for performance but good for implementation (easy:)).

```public string FinalEncription(string L0, string R0, Keys keys, bool IsReverse)
{
string Ln = "", Rn = "", Ln_1 = L0, Rn_1 = R0;
int i = 0;
if (IsReverse == true)
{
i = 15;
}
while (this.IsEnough(i, IsReverse))
{
Ln = Rn_1;
Rn = this.XOR(Ln_1, this.f(Rn_1, keys.Kn[i]));
//Next Step of L1, R1 is L2 = R1, R2 = L1 + f(R1, K2), hence,
//value of Step1's Ln, Rn is Rn_1, Ln_1 in Step2.
Ln_1 = Ln;
Rn_1 = Rn;
if (IsReverse == false)
{
i += 1;
}
else
{
i -= 1;
}
}
string R16L16 = Rn + Ln;
string Encripted_Text = this.DoPermutation(R16L16, DESData.ip_1);
return Encripted_Text;
}```

It's the final process of encryption.

The "`IsReverse`" flag is for using the same method for encryption and decryption.

#### How AES Works in SimpleCryptographer

It's hard to describe AES in detail for me. But I think flash animation that I linked above will be a great help. So I describe the basic building blocks of the Simple Cryptographer.

In AES, it uses a matrix-like data structure, state, so I designed a matrix-like class:

```class Matrix
{
#region Private Fields
private string[,] matrix;
private int rows = 0;
private int columns = 0;
#endregion
#region Constructor
public Matrix(int rows, int columns)
: this("", rows, columns)
{
}
public Matrix(string text)
: this(text, 4, 4)
{
}
public Matrix(string text, int rows, int columns)
{
if (text.Length != columns * rows * 8)
{
text = text.PadRight(columns * rows * 8 - text.Length, '0');
}
matrix = new string[rows, columns];
int count = 0;
this.rows = rows;
this.columns = columns;
for (int i = 0; i < columns; i++)
{
for (int j = 0; j < rows; j++)
{
matrix[j, i] = text.Substring(count * 8, 8);
count++;
}
}
}
#endregion
#region Properties, Indexer
public int Rows
{
get
{
return rows;
}
}
public int Columns
{
get
{
return columns;
}
}
public string this[int i, int j]
{
get
{
return matrix[i, j];
}
set
{
//If it gets hexa decimal, convert it to binary decimal.
if (value.Length == 2)
{
matrix[i, j] = BaseTransform.FromHexToBinary(value);
}
else if (value.Length == 8)
{
matrix[i, j] = value;
}
}
}
#endregion
#region Overrided ToString method
public override string ToString()
{
StringBuilder text = new StringBuilder(128);
if (matrix != null)
{
for (int j = 0; j < columns; j++)
{
for (int i = 0; i < rows; i++)
{
text.Append(matrix[i, j]);
}
}
}
return text.ToString();
}
#endregion
#region one row operation
public string[] getRow(int rowindex)
{
string[] row = new string[this.columns];
if (rowindex > this.rows)
{
throw new IndexOutOfRangeException("It's out of index.");
}
for (int i = 0; i < this.columns; i++)
{
row[i] = matrix[rowindex, i];
}
return row;
}
public void setRow(string[] row, int rowindex)
{
if (rowindex > this.rows)
{
throw new IndexOutOfRangeException("It's out of index.");
}
for (int i = 0; i < this.columns; i++)
{
matrix[rowindex, i] = row[i];
}
}
#endregion
#region one column operation
public string[] getWord(int wordindex)
{
string[] word = new string[this.rows];
if (wordindex > this.rows)
{
throw new IndexOutOfRangeException("It's out of index.");
}
for (int i = 0; i < this.rows; i++)
{
word[i] = matrix[i, wordindex];
}
return word;
}
public void setWord(string[] word, int wordindex)
{
if (wordindex > this.rows)
{
throw new IndexOutOfRangeException("It's out of index.");
}
for (int i = 0; i < this.rows; i++)
{
matrix[i, wordindex] = word[i];
}
}
#endregion
}```

It implements one row calculation, one column(one word in AES) calculation and indexer and I use it all of code in AES implementation like the code below.

```public static Matrix XOR(Matrix a, Matrix b)
{
Matrix c = new Matrix(a.Rows, a.Columns);
for (int i = 0; i < c.Rows; i++)
{
for (int j = 0; j < c.Columns; j++)
{
c[i, j] = MultiplicativeInverse.XOR(a[i, j], b[i, j]);
}
}
return c;
}```

And the module that calculates bit as polynomial that has binary coefficient is multiplicativeinverse class. In AES, it uses multiplication on GF(28).

```public static string GetInverse(string text1, string text2, string mx, int n)
{
string[] multiplyTable = new string[n];
if (text1.IndexOf('1') > text2.IndexOf('1'))
{
string temp = text2;
text2 = text1;
text1 = temp;
}
multiplyTable[0] = text1;
for (int i = 1; i < n; i++)
{
multiplyTable[i] = MultiplicativeInverse.LeftShift2(multiplyTable[i - 1],
n);
if (multiplyTable[i - 1][text1.Length - n].Equals('1'))
{
multiplyTable[i] = MultiplicativeInverse.XOR(multiplyTable[i], mx);
}
}
string Mul_Inverse = "";
for (int i = 0; i < text2.Length; i++)
{
if (text2[i].Equals('1'))
{
if (Mul_Inverse.Equals(""))
{
Mul_Inverse = multiplyTable[(text2.Length - 1/*2*/) - i];
}
else
{
Mul_Inverse = MultiplicativeInverse.XOR(Mul_Inverse,
multiplyTable[(text2.Length - 1/*2*/) - i]);
}
}
}
if (Mul_Inverse.Equals(""))
{
Mul_Inverse = "00000000";
}
return Mul_Inverse;
}```

Mx is reduction modulo, n is greatest degree of a polynomial. If bit string of 1byte "01000100" converts to polynomial on GF(28), x7 + x2. Detailed process of AES and calculate multiplication on GF(28) is better, see book or web site. (I recommend Wikipedia.)

#### Very Very Very Simple Elapsed Time Checking (Appended)

```DateTime start = DateTime.Now;
this.StartSelectedProcess();
DateTime end = DateTime.Now;
TimeSpan result = end - start;
lblProgress.Text = "Elapsed Time : " + result.ToString();```

That's it.

## Using the Code

It has two core classes, `ProcessDES`, `ProcessAES`. As you can see, these classes process encryption and decryption using DES and AES.

These classes are derived from abstract class, `CommonProcess `that has `EncryptionStart`, `DecryptionStart`. These methods are common interface for `ProcessDES`, `ProcessAES`. If I have not misunderstood, changing the algorithm between DES and AES in this program is implemented by Factory Pattern. Using the common interface `CommonProcess`.

Other classes are some building blocks of DES and AES, transform from text to hexadecimal, hexadecimal to text, to binary, and some core building block like multiplication on GF(28), matrix transformation....etc....

All of these algorithms are implemented by string data. It's bad for many times of transformation because it's immutable. If you change value, original value is replaced by the new one, and the old one is garbage. It's the reason for using `StringBuilder `in many times loops like `for `and `while`. I considered it while I wrote the program but I don't assure about performance.

## Points of Interest

I started learning Cryptography two weeks ago, and I made this program. It really helps me in understanding the detail implementation of DES and AES.

## History

• The progressbar for Encryption and Decryption was appended (2007/5/3)
• Count elapsed time was appended (2007/5/8)
• Count detailed elapsed time that is more than a second that just shows the result time at the end of the process was appended (2007/5/9)
• Fix bug that it cuts some texts out during decryption (2007/5/10)
• Check an input key to see whether it is hexadecimal or not (2007/5/21)

## Share

 Web Developer Korea (Republic of)
I'm a super-elementary programmer.
I live in Suwon, Republic of Korea.
And i'm not very good at English.
hahaha!!!

## You may also be interested in...

 Re: Find a key of encryption injector8-Sep-12 23:17 injector 8-Sep-12 23:17
 For suggestion Ratika Agarwal17-Sep-11 4:23 Ratika Agarwal 17-Sep-11 4:23
 Simple Cryptographer -AES large file encryption in C# GaneshKale221-Jul-11 21:17 GaneshKale22 1-Jul-11 21:17
 Inconsistent accessibility: parameter type 'SimpleCryptographer.ProgressInitArgs' GaneshKale2217-Mar-11 22:20 GaneshKale22 17-Mar-11 22:20
 Cant work with pptx file dtmhau28-Sep-10 8:15 dtmhau 28-Sep-10 8:15
 My vote of 1 goxy6127-Aug-10 0:11 goxy61 27-Aug-10 0:11
 implimenting other DES modes jazzman36029-Dec-09 20:13 jazzman360 29-Dec-09 20:13
 Re: implimenting other DES modes Mr.Darcy20-Jan-10 20:01 Mr.Darcy 20-Jan-10 20:01
 Re: implimenting other DES modes Mr.Darcy20-Jan-10 20:17 Mr.Darcy 20-Jan-10 20:17
 My vote of 2 dein.Tod23-Dec-09 15:53 dein.Tod 23-Dec-09 15:53
 Eror in Microsoft Visual Studio 2005 yoyo_merivano1-Apr-09 15:47 yoyo_merivano 1-Apr-09 15:47
 Re: Eror in Microsoft Visual Studio 2005 Mr.Darcy22-Apr-09 22:39 Mr.Darcy 22-Apr-09 22:39
 Why does DES Decryption gives same result even if Key changes / Data Changes etc prakash natarajan11-Mar-09 23:05 prakash natarajan 11-Mar-09 23:05
 Re: Why does DES Decryption gives same result even if Key changes / Data Changes etc Mr.Darcy22-Apr-09 23:13 Mr.Darcy 22-Apr-09 23:13
 Re: Why does DES Decryption gives same result even if Key changes / Data Changes etc giangxe14-Aug-11 1:40 giangxe 14-Aug-11 1:40
 Inconsistent accessibility: parameter type 'SimpleCryptographer.ProgressInitArgs' ambatisreedhar17-Feb-09 3:36 ambatisreedhar 17-Feb-09 3:36
 Re: Inconsistent accessibility: parameter type 'SimpleCryptographer.ProgressInitArgs' kobusdb12-Mar-09 1:48 kobusdb 12-Mar-09 1:48
 Re: Inconsistent accessibility: parameter type 'SimpleCryptographer.ProgressInitArgs' Mr.Darcy22-Apr-09 22:42 Mr.Darcy 22-Apr-09 22:42
 Re: Inconsistent accessibility: parameter type 'SimpleCryptographer.ProgressInitArgs' Member 82893606-May-12 5:14 Member 8289360 6-May-12 5:14
 Thanks Arn.zhan25-Oct-08 20:26 Arn.zhan 25-Oct-08 20:26
 Re: Thanks Mr.Darcy27-Oct-08 21:45 Mr.Darcy 27-Oct-08 21:45
 triple des elhombrecaiman21-Oct-08 0:08 elhombrecaiman 21-Oct-08 0:08
 Re: triple des Mr.Darcy21-Oct-08 15:05 Mr.Darcy 21-Oct-08 15:05
 Encrypt and Decrypt .accdb file Member 390465314-Oct-08 0:54 Member 3904653 14-Oct-08 0:54
 Re: Encrypt and Decrypt .accdb file Mr.Darcy21-Oct-08 15:02 Mr.Darcy 21-Oct-08 15:02
 Error in VS2008 aldo hexosa8-Jul-08 17:11 aldo hexosa 8-Jul-08 17:11
 Re: Error in VS2008 Mr.Darcy8-Jul-08 18:09 Mr.Darcy 8-Jul-08 18:09
 Compatibility with other implementation Member 46881151-Jan-08 6:51 Member 4688115 1-Jan-08 6:51
 Re: Compatibility with other implementation Mr.Darcy1-Jan-08 20:17 Mr.Darcy 1-Jan-08 20:17
 My contribution mony8230-Nov-07 11:39 mony82 30-Nov-07 11:39
 Re: My contribution Mr.Darcy1-Jan-08 20:05 Mr.Darcy 1-Jan-08 20:05
 Great effort! CoolTechie20-Oct-07 3:10 CoolTechie 20-Oct-07 3:10
 Broken unicode decryption litpuvn12-Jun-07 16:21 litpuvn 12-Jun-07 16:21
 Re: Broken unicode decryption litpuvn12-Jun-07 16:23 litpuvn 12-Jun-07 16:23
 Hello Mr Darcy [modified] ahmet35317-May-07 18:08 ahmet353 17-May-07 18:08
 Re: Hello Mr Darcy Mr.Darcy20-May-07 17:23 Mr.Darcy 20-May-07 17:23
 Problem with DES secret key sortgnz16-May-07 6:24 sortgnz 16-May-07 6:24
 Re: Problem with DES secret key Mr.Darcy16-May-07 18:46 Mr.Darcy 16-May-07 18:46
 Re: Problem with DES secret key Markku Hassinen7-Jun-07 2:25 Markku Hassinen 7-Jun-07 2:25
 Hi Broam, ahmet35313-May-07 22:05 ahmet353 13-May-07 22:05
 Thanks again,Mr Darcy [modified] ahmet35313-May-07 3:03 ahmet353 13-May-07 3:03
 Re: Thanks again,Mr Darcy Mr.Darcy13-May-07 20:28 Mr.Darcy 13-May-07 20:28
 Hi Mr. Darcy ahmet35312-May-07 7:03 ahmet353 12-May-07 7:03
 Re: Hi Mr. Darcy Mr.Darcy13-May-07 1:58 Mr.Darcy 13-May-07 1:58
 Hi Mr.Darcy ahmet35311-May-07 10:38 ahmet353 11-May-07 10:38
 Hi Ahmet. [modified] Mr.Darcy11-May-07 17:43 Mr.Darcy 11-May-07 17:43
 Hello Again Mr. Darcy ahmet35310-May-07 12:21 ahmet353 10-May-07 12:21
 Re: Hello Again Mr. Darcy Mr.Darcy10-May-07 19:49 Mr.Darcy 10-May-07 19:49
 an nyeong ha se yo,Mr. Darcy [modified] ahmet3539-May-07 5:53 ahmet353 9-May-07 5:53
 Re: an nyeong ha se yo,Mr. Darcy Mr.Darcy9-May-07 23:43 Mr.Darcy 9-May-07 23:43
 Last Visit: 31-Dec-99 19:00     Last Update: 17-Nov-17 9:34 Refresh 12 Next »