There are quite a few problem with the code shared, they are:
- How will you decrypt the encrypted text if you are using rand()/srand() functions.
- file[i] = rand() + 26;
Here you are just dumping any character value and than dumping into the file, which doesn't make any sense, you need to encrypt some text.
I am attaching a simple sample code with Ceaser cipher[type of substitution ciper] for your reference. whose output will be as follow:
testtest 123123 TESTTEST
tbwxatzd 164904 AOWPTBWX
testtest 123123 TESTTEST
#include <stdio.h>
#include <string.h>
static char key[] = "helloworld";
int Encrypt(char *aText,char *aKey)
{
int lTextlen = strlen(aText);
int lKeylen = strlen(aKey);
int lCount,lShift;
int lCount1 = 0;
for(lCount = 0; lCount < lTextlen;lCount++)
{
if(aText[lCount] >= 'a' && aText[lCount] <= 'z')
{
lShift = aKey[lCount1] % 26;
aText[lCount] = ((aText[lCount] + lShift - 97) % 26) + 97;
}
else if(aText[lCount] >= 'A' && aText[lCount] <= 'Z')
{
lShift = aKey[lCount1] % 26;
aText[lCount] = ((aText[lCount] + lShift - 65) % 26) + 65;
}
else if(aText[lCount] >= '0' && aText[lCount] <= '9')
{
lShift = aKey[lCount1] % 10;
aText[lCount] = ((aText[lCount] + lShift - 48) % 10) + 48;
}
else
{
}
lCount1 = (lCount1 + 1) % lKeylen;
}
}
int Decrypt(char *aText,char *aKey)
{
int lTextlen = strlen(aText);
int lKeylen = strlen(aKey);
int lCount,lShift;
int lCount1 = 0;
for(lCount = 0; lCount < lTextlen;lCount++)
{
if(aText[lCount] >= 'a' && aText[lCount] <= 'z')
{
lShift = 26 - (aKey[lCount1] % 26);
aText[lCount] = ((aText[lCount] + lShift - 97) % 26) + 97;
}
else if(aText[lCount] >= 'A' && aText[lCount] <= 'Z')
{
lShift = 26 - (aKey[lCount1] % 26);
aText[lCount] = ((aText[lCount] + lShift - 65) % 26) + 65;
}
else if(aText[lCount] >= '0' && aText[lCount] <= '9')
{
lShift = 10 - (aKey[lCount1] % 10);
aText[lCount] = ((aText[lCount] + lShift - 48) % 10) + 48;
}
else
{
}
lCount1 = (lCount1 + 1) % lKeylen;
}
}
int main()
{
char plaintext[] = "testtest 123123 TESTTEST";
printf("%s\n",plaintext);
Encrypt(plaintext,key);
printf("%s\n",plaintext);
Decrypt(plaintext,key);
printf("%s\n",plaintext);
return 0;
}