5.13.2009

Affine Cipher written in C#

The following code written in C# encrypts and decrypts using the Affine Cipher. For more information, check out Making, Breaking Codes by Paul Garrett. All questions/comments are always appreciated.



///
/// This function takes plain text and encrypts it using the Affine Cipher
/// e(x) = (ax + b)(mod m). Note: a & m should be coprime.
///
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!");
}

10 comments:

  1. hi... how could i implement the encryption and decryption of affine cipher using matlab... could u help me pls or give an outline of the idea of wat should be done..

    ReplyDelete
    Replies
    1. Ah yes, a homework problem. Here's a link that should help you out. http://practicalcryptography.com/ciphers/affine-cipher/

      Delete
  2. please reply as early as possible... please

    ReplyDelete
  3. I dont understand the significance of int x = Convert.ToInt32(c - 65);
    Please explain

    ReplyDelete
    Replies
    1. It's because the ASCII table contains capital letters starting at code 65, so I'm using this number as an offset for the chars array index. Do a search on ASCII Codes and you will see why.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. I am implementing this in java. I'm stuck in "foreach" loop. Could you help me please.

    ReplyDelete
    Replies
    1. In java, you would have to use Integer.parseInt() and (char) to cast. I hope this makes sense.

      Delete
  6. If possible, can you give this in c++?

    ReplyDelete