-
Notifications
You must be signed in to change notification settings - Fork 1
/
CesarCypher.cs
69 lines (66 loc) · 3.34 KB
/
CesarCypher.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
using System;
namespace Codenation.Challenge
{
public class CesarCypher : ICrypt, IDecrypt
{
int key = 3; //key to crypting and decrypting
public string Crypt(string message)
{
int ascii = 0; // variable utilized to see the character in decimal numbers see ascii http://www.asciitable.com/
if (message == null) //Null exception implementations
throw new ArgumentNullException();
char[] messagechar = (message.ToLower()).ToCharArray(); //separate the string in an array of char and put all letters in lower case
int i = 0; //counter of the array
string crypting = ""; //initialize the crypting
foreach (char character in messagechar)
{
ascii = messagechar[i];
if (ascii >= 48 && ascii <=57) //number 0 = 48 ascii ... 9 =57 ascii
ascii = messagechar[i];
else if (ascii == 32) // space = 32 ascii
ascii = messagechar[i];
else if (ascii < 97 || ascii > 122) //alphabet char a = 97 ascii ... z=122 ascii
throw new ArgumentOutOfRangeException(); //special character exception
else
{
if (messagechar[i] + key > 'z') //crypting
ascii = messagechar[i] + key - ('z' - 'a' + 1); //crypting
else
ascii = messagechar[i] + key; //crypting
}
i++;
crypting += ((char)ascii).ToString(); //appending char to string
}
return crypting; //return the criptedmessage
}
public string Decrypt(string cryptedmessage) //The decrypting is very similar but the key has the opposite signal
{
int ascii = 0;
if (cryptedmessage == null)
throw new ArgumentNullException();
char[] messagechar = (cryptedmessage.ToLower()).ToCharArray();
int i = 0;
string decrypting = null;
foreach (char character in messagechar)
{
ascii = messagechar[i];
if (ascii >= 48 && ascii <= 57)
ascii = messagechar[i];
else if (ascii == 32)
ascii = messagechar[i];
else if (ascii < 97 || ascii > 122)
throw new ArgumentOutOfRangeException();
else
{
if (messagechar[i] - key < 'a' - 0)
ascii = ('z' - 'a' +1) + messagechar[i] - key;
else
ascii = messagechar[i] - key;
}
i++;
decrypting = decrypting + ((char)ascii).ToString();
}
return decrypting;
}
}
}