-
Notifications
You must be signed in to change notification settings - Fork 1
/
RailFence.cs
87 lines (70 loc) · 2.08 KB
/
RailFence.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
namespace PlayFair
{
class RailFence:Security
{
readonly int key;
public RailFence(int key)
{
this.key = key;
}
#region Public Methods
public override string Encrypt(string plainText)
{
return Process(plainText, Mode.Encrypt);
}
public override string Decrypt(string cipherText)
{
return Process(cipherText, Mode.Decrypt);
}
#endregion
#region Private Methods
private string Process(string message, Mode mode)
{
int rows = key;
int columns = (int)Math.Ceiling((double)message.Length / (double)rows);
char[,] matrix = FillArray(message, rows, columns, mode);
string result = "";
foreach (char c in matrix)
{
result += c;
}
return result;
}
private char[,] FillArray(string message, int rowsCount, int columnsCount, Mode mode)
{
int charPosition = 0;
int length = 0, width = 0;
char[,] matrix = new char[rowsCount, columnsCount];
switch (mode)
{
case Mode.Encrypt:
length = rowsCount;
width = columnsCount;
break;
case Mode.Decrypt:
matrix = new char[columnsCount, rowsCount];
width = rowsCount;
length = columnsCount;
break;
}
for (int i = 0; i < width; i++)
{
for (int j = 0; j < length; j++)
{
if (charPosition < message.Length)
{
matrix[j, i] = message[charPosition];
}
else
{
matrix[j, i] = ' ';
}
charPosition++;
}
}
return matrix;
}
#endregion
}
}