我正在编写加密和解密函数,其工作方式如下:
encrypt("string") -> "encryptedString"
decrypt("encryptedString") -> "string"
但是,运行它们时我得到的结果很奇怪。
在我的示例中,我正在加密ab#z,A1BZ
以便获得:bc#a,Z1AY
,反之亦然(解密)
运行代码时,得到以下输出:
Question 3a (encrypt): bc#a,Z1AY
Question 3b (decrypt): ab#z,A1BZcuments�v�j�
我想强调一下,该功能似乎在正确地完成其工作。请注意,ab#z,A1BZ
是解密输出的一部分。那部分是正确的。但是后面紧跟cuments�v�j�
decrypt("bc#a,Z1AY")
仅应产生ab#z,A1BZ
以下是功能:
char* encrypt(const char* plaintext){
char* ciphertext = malloc((strlen(plaintext) + 1) * sizeof(char));
for (int i = 0; i < strlen(plaintext); i++){
if (islower(plaintext[i])){
char c;
if (plaintext[i] == 'z'){
c = 'a';
}
else {
c = plaintext[i] + 1;
}
ciphertext[i] = c;
}
else if (isupper(plaintext[i])){
char c;
if (plaintext[i] == 'A'){
c = 'Z';
}
else {
c = plaintext[i] - 1;
}
ciphertext[i] = c;
}
else {
ciphertext[i] = plaintext[i];
}
}
return ciphertext;
}
char* decrypt(const char* ciphertext){
char* plaintext = malloc((strlen(ciphertext) + 1) * sizeof(char));
for (int i = 0; i < strlen(ciphertext); i++){
if (islower(ciphertext[i])){
char c;
if (ciphertext[i] == 'a'){
c = 'z';
}
else {
c = ciphertext[i] - 1;
}
plaintext[i] = c;
}
else if (isupper(ciphertext[i])){
char c;
if (ciphertext[i] == 'Z'){
c = 'A';
}
else {
c = ciphertext[i] + 1;
}
plaintext[i] = c;
}
else {
plaintext[i] = ciphertext[i];
}
}
return plaintext;
}
这是呼叫/驱动程序代码:
char* ciphertext = encrypt("ab#z,A1BZ");
char* plaintext = decrypt(ciphertext);
printf("Question 3a (encrypt): %s\n",ciphertext);
printf("Question 3b (decrypt): %s\n",plaintext);
free(ciphertext);
free(plaintext);
其中SIZE
被定义为8