/
07. EncryptionKey.cs
57 lines (46 loc) · 1.55 KB
/
07. EncryptionKey.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
/*Write a program that encodes and decodes a string using given encryption key (cipher).
* The key consists of a sequence of characters. The encoding/decoding is done by performing XOR (exclusive or)
* operation over the first letter of the string with the first of the key, the second – with the second, etc.
* When the last key character is reached, the next is the first.*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class EncryptionKey
{
static void Main()
{
string str = "KO? He!";
string key = "The key";
Console.Write("Encrypted => ");
string encrypted = Encrypt(str, key);
Console.WriteLine(encrypted);
Console.Write("Decrypted => ");
string deCrypt = DeCrypt(encrypted, key);
Console.WriteLine(deCrypt);
}
static string Encrypt(string str, string key)
{
char[] strArr = str.ToCharArray();
char[] keyArr = new char[strArr.Length];
StringBuilder encrypted = new StringBuilder();
for (int i = 0, k = 0; i < keyArr.Length; k++, i++)
{
if (!(k < key.Length))
{
k = 0;
}
keyArr[i] = key[k];
}
for (int i = 0; i < strArr.Length; i++)
{
encrypted.Append((char)(strArr[i] ^ keyArr[i]));
}
return encrypted.ToString();
}
static string DeCrypt(string str, string key)
{
return Encrypt(str, key).ToString();
}
}