3
Good afternoon,
I’m developing a basic encryption code (Caesar’s cipher) in C.
I am using the logic of traversing 2 vectors: vetText and vetLetras, where the comparison of char and then replace it with 3 forward positions in the old Etras, but I’m not succeeding. The code compiles, but at the time of running is asking for text entries to be encrypted several times (entries larger than the vector size stipulated by me).
Code:
#include<stdio.h>
int main (){
#define tamanhoTexto 4
#define qtdLetras 26
int i = 0, j = 0;
char vetTexto[tamanhoTexto];
char vetLetras[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
for(i=0; i<tamanhoTexto;i++){ //Lendo o texto a ser encriptado
scanf ("%c", &vetTexto[tamanhoTexto]);
}
for (i = 0; i < tamanhoTexto; i++){ //Varrendo os 2 vetores fazendo a busca de letras correspondentes
for (j = 0; j < qtdLetras; j++){
if(vetTexto[i] == vetLetras[j] && j+ 3 <qtdLetras){ //j+3(deslocamento) não pode sair do vetor letras
vetTexto[i] = vetLetras[j+ 3];
}else{
j = j + 3;
j = j - qtdLetras; //caso saia, faço a soma e tiro 26, pra voltar ao começo.
vetTexto[i] = vetLetras[j];
}
}
}
for (i = 0; i < tamanhoTexto; i++){ //impressão do texto criptografado
printf ("%c", vetTexto[i]);
}
return 0;
}
I’ve seen some similar questions here on the forum, but they’re using a different logic and syntax than mine.
Being a little more objective: my doubts are:
- Why the code doesn’t work?
- The logic is correct?
- There is a better way to apply this type of C encryption?
Thank you for your attention.
Hey, it’s all right. I already made this algorithm in php, if you want to take a look... https://github.com/flhorizonte/caesar-cipher-algorithm/blob/master/CifraCesar.php
– Felipe Horizonte