-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCipher.cs
98 lines (85 loc) · 2.58 KB
/
Cipher.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
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Threading;
class Cipher{
static void Main(string[] args){
Console.WriteLine("<---------------Cipher---------------->");
Console.WriteLine("Created by Morasiu (morasiu2@gmail.com)");
string text = GetText();
string key = GetKey();
string option = ChooseOption();
if (option == "1")
Encrypt(text, key);
else if (option == "2")
Decrypt(text, key);
Console.ReadKey();
}
static void Encrypt(string text, string key){
string encText = "";
int keyIndex = 0;
if (key.Length == 0){
Console.WriteLine("Empty key");
} else {
for(int i = 0; i < text.Length; i++){
char originLetter = text[i];
int asciiOrigin = originLetter;
char keyChar = key[keyIndex];
int asciiKey = keyChar - 32;
int asciiEnc = asciiOrigin + asciiKey;
if (asciiEnc > 126)
asciiEnc = asciiEnc - 126 + 32;
char encChar = (char) (asciiEnc);
keyIndex++;
if(keyIndex > key.Length -1)
keyIndex = 0;
encText += encChar.ToString();
}
Console.Write("Result:\n>" + encText + "<\n");
}
}
static void Decrypt(string text, string key){
string decText = "";
int keyIndex = 0;
if (key.Length == 0){
Console.WriteLine("Empty key");
} else {
for(int i = 0; i < text.Length; i++){
char originLetter = text[i];
int asciiOrigin = originLetter;
char keyChar = key[keyIndex];
int asciiKey = keyChar - 32;
int asciiDec = asciiOrigin - asciiKey;
if (asciiDec < 32)
asciiDec = 126 - (32 - asciiDec);
char decChar = (char) (asciiDec);
keyIndex++;
if(keyIndex > key.Length -1)
keyIndex = 0;
decText += decChar.ToString();
}
Console.Write("Result:\n>" + decText + "<\n");
}
}
static string ChooseOption(){
string option;
do {
Console.WriteLine("1. Encrypting\n2. Decrypting");
Console.Write("Choose option: ");
option = Console.ReadLine();
} while (option != "1" && option != "2");
return option;
}
static string GetText(){
//I know. I looks useless. I could just add this in Main, but hey it looks nice.
string text;
Console.WriteLine("Enter your text below and press Enter.");
text = Console.ReadLine();
return text;
}
static string GetKey(){
//"You could write this in one line". Yeah, yeah, but it is so pretty :)
string key;
Console.WriteLine("Enter your key below and press Enter.");
key = Console.ReadLine();
return key;
}
}