首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >异或加密失败

异或加密失败
EN

Stack Overflow用户
提问于 2013-09-26 16:14:52
回答 1查看 358关注 0票数 1

答案:

我必须创建一个单独的解密函数,使用"rb“打开加密文件,然后在加密函数中使用"wb”将加密的数据写入文件。

我的Xor加密有问题。当加密文件中的数据时,加密工作正常,但当我试图解密数据时,加密会失败。问题是,fgetc函数只读取第一行和第二行,无法解密第二行的50%。

示例:

法线:

代码语言:javascript
运行
复制
This is a text, This is a text

This is a text, This is a text

加密

代码语言:javascript
运行
复制
a¦_ÖÞ`×ûù‡ûÛ(‹Pñ»FŒ§U®7!¼ªãŸ<çϱ\Î8ðs6Öã`GÒFAªÓV/Ç1t

解密

代码语言:javascript
运行
复制
This is a text, This is a text

This is a text, ±Åãl«åé»–o„ F

我用断点检查了代码,发现问题是fgetc在第二行之后停止读取文件,但我不知道为什么。也许我的算法有问题。

代码:

代码语言:javascript
运行
复制
int encrypt_file(const char *filename, const char *key)
{
    int i               = 0;
    size_t key_len      = strlen(key);
    size_t key_count    = 0;
    size_t num_bytes    = 0;

    int *data = NULL;
    int byte = 0;

    FILE *file;

    fopen_s(&file, filename, "r");

    if ( file != NULL )
    {
        // get file size / number of bytes
        fseek(file, 0L, SEEK_END);
        num_bytes = ftell(file);
        fseek(file, 0L, SEEK_SET);

        // allocate enough memory for the data
        data = (int*)malloc(sizeof(int) *num_bytes);

        // stores the data from the file in the array
        while ( (data[i++] = fgetc(file)) != EOF );

        // encrypt the data
        for ( i = 0; i < num_bytes; i++ ) {
            data[i] = data[i]^key[key_count++];

            if ( key_count == key_len ) {
                key_count = 0;
            }
        }

        fclose(file);
        fopen_s(&file, filename, "w");

        // write the data from the array to the same file
        for ( i = 0; i < num_bytes; i++ ) {
            fputc(data[i], file);
        }

        fclose(file);
        return 0;
    }
    else
    {
        return 1;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-26 16:32:20

由于加密数据不再是文本,您应该在打开I/O加密文件时使用"wb""rb"

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19033411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档