The **affine cipher** is a type of monoalphabetic substitution cipher, wherein each letter in an alphabet is mapped to its numeric equivalent, encrypted using a simple mathematical function, and converted back to a letter. The formula used means that each letter encrypts to one other letter, and back again, meaning the cipher is essentially a standard substitution cipher with a rule governing which letter goes to which. As such, it has the weaknesses of all substitution ciphers. Each letter is enciphered with the function , where is the magnitude of the shift.

For more information on affine cipher visit here

Following code is written in c# which has the affine cipher algorithm

- public static string AffineEncrypt(string plainText, int a, int b)
- {
- string cipherText = "";
- // Put Plain Text (all capitals) into Character Array
- char[] chars = plainText.ToUpper().ToCharArray();
- // Compute e(x) = (ax + b)(mod m) for every character in the Plain Text
- foreach (char c in chars)
- {
- int x = Convert.ToInt32(c - 65);
- cipherText += Convert.ToChar(((a * x + b) % 26) + 65);
- }
- return cipherText;
- }
- ///
- /// This function takes cipher text and decrypts it using the Affine Cipher
- /// d(x) = aInverse * (e(x) b)(mod m).
- ///
- public static string AffineDecrypt(string cipherText, int a, int b)
- {
- string plainText = "";
- // Get Multiplicative Inverse of a
- int aInverse = MultiplicativeInverse(a);
- // Put Cipher Text (all capitals) into Character Array
- char[] chars = cipherText.ToUpper().ToCharArray();
- // Computer d(x) = aInverse * (e(x) b)(mod m)
- foreach (char c in chars)
- {
- int x = Convert.ToInt32(c - 65);
- if (x - b < 0) x = Convert.ToInt32(x) + 26;
- plainText += Convert.ToChar(((aInverse * (x - b)) % 26) + 65);
- }
- return plainText;
- }
- ///
- /// This functions returns the multiplicative inverse of integer a mod 26.
- ///
- public static int MultiplicativeInverse(int a)
- {
- for (int x = 1; x < 27; x++)
- {
- if ((a * x) % 26 == 1)
- return x;
- }
- throw new Exception("No multiplicative inverse found!");
- }

**Happy Coding !!!!**

Hi Sammani,

ReplyDeleteMay i have this complete code of Affine cypher please. I need to finish one project but i am far from programming at all.

mali

Hi Mali,

DeleteCan you send me your email address. I will email you the source code.

Thank you very much Sammani i really appreciate.

DeleteMy email is malipylli@gmail.com

May i have this complete code of Affine cypher please.

DeleteMy email is mneer54@gmail.com

thx u dude... happy coding

ReplyDeleteyour code is the best thing i found on the internet. well done.

ReplyDeleteMay i have this complete code of Affine cypher please.

DeleteMy email is tacisercetin@gmail.com

can you please email me this compelete code .

ReplyDeletealfiamushtaq18@gmail.com

please send your complete code including libraries to the following email. i will really appreciate it sammani

ReplyDeletewajeeha094@gmail.com