|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace SecurityLibrary |
| 8 | +{ |
| 9 | + public class Ceaser : ICryptographicTechnique<string, int> |
| 10 | + { |
| 11 | + public string alphabet = "abcdefghijklmnopqrstuvwxyz"; |
| 12 | + |
| 13 | + public int letterNum(char letter) // O(1) |
| 14 | + { |
| 15 | + for (int i = 0; i < 26; i++) |
| 16 | + { |
| 17 | + if (letter == alphabet[i]) return i; |
| 18 | + } |
| 19 | + |
| 20 | + return -1; |
| 21 | + } |
| 22 | + public string Encrypt(string plainText, int key) |
| 23 | + { |
| 24 | + int PTLength = plainText.Length; |
| 25 | + string CT = ""; |
| 26 | + for (int i = 0; i < PTLength; i++) // O(N) |
| 27 | + { |
| 28 | + if (char.IsLetter(plainText[i])) |
| 29 | + { |
| 30 | + int letterIndx = ((key + letterNum(plainText[i]))%26); |
| 31 | + CT += char.ToUpper(alphabet[letterIndx]); |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + CT += plainText[i]; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return CT; |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + public string Decrypt(string cipherText, int key) |
| 44 | + { |
| 45 | + cipherText = cipherText.ToLower(); |
| 46 | + int CTLength = cipherText.Length; |
| 47 | + string PT = ""; |
| 48 | + for (int i = 0; i < CTLength; i++) // O(N) |
| 49 | + { |
| 50 | + if (char.IsLetter(cipherText[i])) |
| 51 | + { |
| 52 | + int letterIndx = ((letterNum(cipherText[i]) - key) % 26); |
| 53 | + if(letterIndx < 0) letterIndx += 26; |
| 54 | + PT += alphabet[letterIndx]; |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + PT += cipherText[i]; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return PT; |
| 63 | + } |
| 64 | + |
| 65 | + public int Analyse(string plainText, string cipherText) // O(1) |
| 66 | + { |
| 67 | + if (plainText.Length != cipherText.Length) return -1; |
| 68 | + int letterPN = letterNum(plainText[0]); |
| 69 | + int letterCN = letterNum(char.ToLower(cipherText[0])); |
| 70 | + |
| 71 | + return ((letterCN - letterPN) < 0) ? (letterCN - letterPN) + 26 : (letterCN - letterPN) % 26; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments