The C++ Vigener cipher does not encrypt arrays as it should
I'm starting to learn the pros and I can't cope with the task for the vigener cipher. The function works, but it doesn't encrypt properly. String and vector are not allowed
#include <iostream> // For Input and Output
#include <fstream> // For file input and output
#include <string.h>
using namespace std;
const int wordLength = 81;
void encodeText(char text[wordLength], char key[wordLength]){
int textLen = strlen(text);
int keyLen = strlen(key);
int i, j;
char newKey[textLen];
char encryptedText[textLen];
//новый ключ
for(i = 0, j = 0; i < textLen; ++i, ++j){
if(j == keyLen){
j = 0;
}
newKey[i] = key[j];
}
newKey[i] = '\0';
//шифровка
for(i = 0; i < textLen; i++){
if (text[i] != ' '){
encryptedText[i] = ((text[i] + newKey[i]) % 26);
encryptedText[i] += 'a';
}
else{
encryptedText[i] = ' ';
}
}
encryptedText[i] = '\0';
cout << newKey << endl;
cout << text << endl;
cout << encryptedText << endl;
}
int main(){
cout << "Введи текст для шифрования: ";
char textToEncode[wordLength];
cin.getline(textToEncode, wordLength);
cout << "Введи ключ: ";
char keyword[wordLength];
cin.getline(keyword,wordLength );
cout << "Ключ, текст и шифр: \n";
encodeText(textToEncode, keyword);
return 0;
}
For example, the code outputs:
Введи текст для шифрования: all generalizations are false
Введи ключ: secret
Ключ, текст и шифр:
secretsecretsecretsecretsecre
all generalizations are false
ebz wjrufdbndqhlesw ouu jqzvu
The code should output:
secretsecretsecretsecretsecre
all generalizations are false
spn kxfitrpbrevzsgk cii xenji
1
1 answers
Answer by Yuri Kozlov:
It is necessary to replace this encryptedText[i] = ((text[i] + newKey[i]) % 26)
with this encryptedText[i] = (((text[i] - 'a') +(newKey[i] - 'a')) % 26)
.
-1
Author: joker, 2020-07-17 04:43:51