I had originally a Caesar's cypher code, which looked like this:
#include <stdio.h>
#include <string.h>
int main (int argc, char const *argv[])
{
printf("Insira a frase:\n");
char frase [256];
//strcpy(frase, argv[1]);
scanf("%s", frase);
int size = (int)strlen(frase);
printf("Insira o tamanho da divergência: \n");
int diff = 0;
scanf("%i", &diff);
char fraseout [size+1];
int i = 0;
for (i = 0; i<=size-1; i++)
{
int val = (int)frase[i];
if (val + diff > 126)
{
while (val + diff >126)
{
val = 31+diff-(126-val);
}
}
else if (val + diff < 32)
{
while (val + diff < 32)
{
val = 127 + diff+(val-32);
}
}
else
{
val +=diff;
}
fraseout [i] = (char)val;
}
fraseout[size] = '\0';
printf("\"%s\" -> \"%s\"\n", frase, fraseout);
return 0;
}
I then decided to turn it into a Vinegere's cypher code, where the codifying number for each character is given by a password and iterates over the length of the word. So, if my word is "abcde" and my password is "zx" the pair (char, diff) would be (a,z)(b,x)(c,z)(d,x)... The code looks as following:
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
/* code */
char senha [256];
if (argv[1] != NULL)
{
strcpy(senha, argv[1]);
}
char frase [256];
printf("Insira a frase: \n");
scanf("%s", frase);
int sizeS = (int)strlen(senha);
int sizeF = (int)strlen(frase);
char fraseout [sizeF+1];
int i;
int j;
for (i=0; i<=sizeF-1; i++)
{
if(j>sizeS)
{
j=0;
}
int valF = (int)frase[i];
int valS = (int)senha[i];
printf(" F = %c = %i \n S = %c = %i\n", frase[i], valF, senha[i], valS);
if (valF+valS > 126)
{
while (valF+valS >126)
{
printf("ValF = %i\n", valF);
printf("ValS = %i\n", valS);
valF = 31 + valS-(valF-126);
printf("NewV = %i\n", valF);
}
}
else if (valF+valS < 32)
{
while (valF+valS<32)
{
valF = 127 + valS+(valF-32);
}
}
else
{
valF += valS;
}
printf("OUT = %i = %c\n",valF, (char)valF);
printf("_________________________________\n");
fraseout[i] = (char)valF;
j++;
}
fraseout[sizeF] = '\0';
printf("\"%s\" -> \"%s\"\n", frase, fraseout);
return 0;
}
For some reason however this code just enters in an infinite loop on the firt while()
statement and I don't get why. How can I fix this?
Two problems I can see:
First, senha[i]
should be senha[j]
.
Second, if (j > sizeS)
should be if (j >= sizeS)
. Otherwise, you'll try to access senha[sizeS]
, which contains the null terminator, not one of the characters in the string.
I think all that code for trying to deal with the addition of the characters going outside the printing range can be replaced with:
valF = 32 + ((valF - 32) + (valS - 32)) % (128-32);