Last active
July 18, 2023 13:41
-
-
Save ozansulukpinar/9fa2a6b958e567f6c20d7ab35778e8e4 to your computer and use it in GitHub Desktop.
Affine Cipher Encoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class Program | |
{ | |
static char[] lowerCaseLetters = new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; | |
public static void Main(string[] args) | |
{ | |
string text = AffineCipher("Affine", 1, 1); | |
Console.WriteLine (text); | |
} | |
private static string AffineCipher(string oldText, int key1, int key2) | |
{ | |
bool? isItUpper = false; | |
char currentLetter = new char(); | |
string newText = ""; | |
char newLetter = new char(); | |
char[] letters = oldText.ToCharArray(); | |
foreach(char letter in letters) { | |
if((int)letter >= 65 && (int)letter <= 90){ | |
isItUpper = true; | |
currentLetter = Char.ToLower(letter); | |
} | |
else if((int)letter >= 97 && (int)letter <= 122){ | |
isItUpper = false; | |
currentLetter = letter; | |
} | |
else{ | |
isItUpper = null; | |
} | |
int index = Array.IndexOf(lowerCaseLetters, currentLetter); | |
if(isItUpper != null){ | |
if ((bool)isItUpper) | |
{ | |
newLetter = FindNewLetter(index, key1, key2, true); | |
} | |
else if (!(bool)isItUpper) | |
{ | |
newLetter = FindNewLetter(index, key1, key2, false); | |
} | |
} | |
else{ | |
newLetter = letter; | |
} | |
newText += newLetter; | |
} | |
return newText; | |
} | |
private static char FindNewLetter(int index, int key1, int key2, bool isItUpper) | |
{ | |
char newLetter = new char(); | |
int newIndex = (key1 * index + key2) % 26; | |
newLetter = lowerCaseLetters[newIndex]; | |
if(isItUpper) | |
newLetter = char.ToUpper(newLetter); | |
return newLetter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment