C 与硬编码输入相比,使用FGET从用户处获取密钥时无法打印密钥流
我正在试验fgets,而不是用一个程序对数组进行硬编码,该程序接受明文和密钥输入,并返回密钥流和加密文本。使用FGET扫描来自用户的密钥会以某种方式更改输出,使其不打印密钥流,而只打印密钥本身。我唯一改变的是,我让用户用fgets输入密钥,而不是用数组硬编码密钥字符串 硬编码(代码片段):C 与硬编码输入相比,使用FGET从用户处获取密钥时无法打印密钥流,c,encryption,fgets,vigenere,C,Encryption,Fgets,Vigenere,我正在试验fgets,而不是用一个程序对数组进行硬编码,该程序接受明文和密钥输入,并返回密钥流和加密文本。使用FGET扫描来自用户的密钥会以某种方式更改输出,使其不打印密钥流,而只打印密钥本身。我唯一改变的是,我让用户用fgets输入密钥,而不是用数组硬编码密钥字符串 硬编码(代码片段): #包括 #包括 内部主(空) { char msg[]=“THECRAZYPROGRAMMER”; 字符键[]=“你好”; int msgLen=strlen(msg),keyLen=strlen(key),
#包括
#包括
内部主(空)
{
char msg[]=“THECRAZYPROGRAMMER”;
字符键[]=“你好”;
int msgLen=strlen(msg),keyLen=strlen(key),i,j;
char newKey[msgLen]、encryptedsg[msgLen]、decryptedMsg[msgLen];
//生成新密钥
对于(i=0,j=0;i
fgets(片段):
#包括
#包括
内部主(空)
{
char-msg[512];
字符键[512];
int msgLen=strlen(msg),keyLen=strlen(key),i,j;
char newKey[msgLen]、encryptedsg[msgLen]、decryptedMsg[msgLen];
fgets(msg,512,标准输入);
fgets(图例512,标准DIN);
//生成新密钥
对于(i=0,j=0;i
查看下面的代码,它对您的fgets
代码进行了一些编辑
#include <stdio.h>
#include <string.h>
int main(void)
{
char msg[512];
char key[512];
fgets(msg, 512, stdin);
fgets(key, 512, stdin);
int msgLen = strlen(msg), keyLen = strlen(key), i, j;
char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];
//generating new key
for(i = 0, j = 0; i < msgLen; ++i, ++j){
if(j == keyLen - 1)
j = 0;
newKey[i] = key[j];
}
newKey[i] = '\0';
printf("Original Message: %s", msg);
printf("\nKey: %s", key);
printf("\nNew Generated Key: %s", newKey);
}
#包括
#包括
内部主(空)
{
char-msg[512];
字符键[512];
fgets(msg,512,标准输入);
fgets(图例512,标准DIN);
int msgLen=strlen(msg),keyLen=strlen(key),i,j;
char newKey[msgLen]、encryptedsg[msgLen]、decryptedMsg[msgLen];
//生成新密钥
对于(i=0,j=0;i
我改变了两件事。首先,我将msgLen
和keyLen
的代码移动到调用fgets
之后,这样就不会占用strlen
的未初始化内存。其次,我纠正了if(j==keylen-1)
行中的一个off-by-one错误,这样就不会在输出中包含给fgets
的换行符
#include <stdio.h>
#include <string.h>
int main(void)
{
char msg[512];
char key[512];
int msgLen = strlen(msg), keyLen = strlen(key), i, j;
char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];
fgets(msg, 512, stdin);
fgets(key, 512, stdin);
//generating new key
for(i = 0, j = 0; i < msgLen; ++i, ++j){
if(j == keyLen)
j = 0;
newKey[i] = key[j];
}
newKey[i] = '\0';
printf("Original Message: %s", msg);
printf("\nKey: %s", key);
printf("\nNew Generated Key: %s", newKey);
}
#include <stdio.h>
#include <string.h>
int main(void)
{
char msg[512];
char key[512];
fgets(msg, 512, stdin);
fgets(key, 512, stdin);
int msgLen = strlen(msg), keyLen = strlen(key), i, j;
char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];
//generating new key
for(i = 0, j = 0; i < msgLen; ++i, ++j){
if(j == keyLen - 1)
j = 0;
newKey[i] = key[j];
}
newKey[i] = '\0';
printf("Original Message: %s", msg);
printf("\nKey: %s", key);
printf("\nNew Generated Key: %s", newKey);
}