///
/// 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!");
}
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..
ReplyDeleteAh yes, a homework problem. Here's a link that should help you out. http://practicalcryptography.com/ciphers/affine-cipher/
Deleteplease reply as early as possible... please
ReplyDeleteThanks a lot!
ReplyDeleteI dont understand the significance of int x = Convert.ToInt32(c - 65);
ReplyDeletePlease explain
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.
DeleteThis comment has been removed by the author.
ReplyDeleteI am implementing this in java. I'm stuck in "foreach" loop. Could you help me please.
ReplyDeleteIn java, you would have to use Integer.parseInt() and (char) to cast. I hope this makes sense.
DeleteIf possible, can you give this in c++?
ReplyDelete