C Programming
I have this function to i want to return the cipher text, but its not working, can anyone try to see what i'm doing wrong.
I need it to return the cipher text.
char* vigenereCipher(char *plainText, char *k)
{
int i;
char cipher;
int cipherValue;
int len = strlen(k);
char *cipherText = (char *)malloc(sizeof(plainText) * sizeof(char));
//Loop through the length of the plain text string
for (i = 0; i < strlen(plainText); i++)
{
//if the character is lowercase, where range is [97 -122]
if (islower(plainText[i]))
{
cipherValue = ((int)plainText[i] - 97 + (int)tolower(k[i % len]) - 97) % 26 + 97;
cipher = (char)cipherValue;
}
else // Else it's upper case, where letter range is [65 - 90]
{
cipherValue = ((int)plainText[i] - 65 + (int)toupper(k[i % len]) - 65) % 26 + 65;
cipher = (char)cipherValue;
}
//Print the ciphered character if it is alphanumeric (a letter)
if (isalpha(plainText[i]))
{
// Assign the cipher to the cipherText instead of printing it.
*cipherText = cipher;
cipherText++;
}
else //if the character is not a letter then print the character (e.g. space)
{
// Assign the character to the cipherText instead of printing it.
*cipherText = plainText[i];
cipherText++;
}
}
printf("%s", cipherText); //<------TRY PRINTING IT HERE AND NOTHING!!!!!
//return cipherText;
return strdup(cipherText);
}
Here, you can check my C++ code.
// C++ code to implement Vigenere Cipher
#include<bits/stdc++.h>
using namespace std;
// This function generates the key in
// a cyclic manner until it's length isi'nt
// equal to the length of original text
string generateKey(string str, string key)
{
int x = str.size();
for (int i = 0; ; i++)
{
if (x == i)
i = 0;
if (key.size() == str.size())
break;
key.push_back(key[i]);
}
return key;
}
// This function returns the encrypted text
// generated with the help of the key
string cipherText(string str, string key)
{
string cipher_text;
for (int i = 0; i < str.size(); i++)
{
// converting in range 0-25
char x = (str[i] + key[i]) %26;
// convert into alphabets(ASCII)
x += 'A';
cipher_text.push_back(x);
}
return cipher_text;
}
// This function decrypts the encrypted text
// and returns the original text
string originalText(string cipher_text, string key)
{
string orig_text;
for (int i = 0 ; i < cipher_text.size(); i++)
{
// converting in range 0-25
char x = (cipher_text[i] - key[i] + 26) %26;
// convert into alphabets(ASCII)
x += 'A';
orig_text.push_back(x);
}
return orig_text;
}
// Driver program to test the above function
int main()
{
string str = "GEEKSFORGEEKS";
string keyword = "AYUSH";
string key = generateKey(str, keyword);
string cipher_text = cipherText(str, key);
cout << "Ciphertext : "
<< cipher_text << "\n";
cout << "Original/Decrypted Text : "
<< originalText(cipher_text, key);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.