【问题标题】:XOR-Encryption works on Code blocks not on Visual Studio 2017XOR-Encryption 适用于不在 Visual Studio 2017 上的代码块
【发布时间】:2017-06-08 22:37:52
【问题描述】:

所以我想在写入 .txt 文件时加密我的数据,所以我从这段代码中选择 XOR-Encryption: Github 因此,当我在代码块中运行时,它会运行并显示以下结果:

Encrypted: :=.43*-:8m2$.a
Decrypted:kylewbanks.com0

Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.

但是当我开始使用 Visual Studio 2017 时,它会显示此错误:

Error (active)  E0059   function call is not allowed in a constant expression   

这意味着我在声明数组时不能放变量,所以有什么方法可以让我的加密在 VS2017 中工作。 我认为问题是当使用常量声明变量时,无论如何强制它或其他易于使用的加密方法,我不需要安全只是为了防止文件中的纯文本。 无论如何,这是唯一的代码:

#include <stdio.h>
#include <string.h>

void encryptDecrypt(char *input, char *output) {
    char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array

    int i;
    for(i = 0; i < strlen(input); i++) {
        output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
    }
}

int main () {
    char baseStr[] = "kylewbanks.com";

    char encrypted[strlen(baseStr)];
    encryptDecrypt(baseStr, encrypted);
    printf("Encrypted:%s\n", encrypted);

    char decrypted[strlen(baseStr)];
    encryptDecrypt(encrypted, decrypted);
    printf("Decrypted:%s\n", decrypted);
}

【问题讨论】:

  • 源代码?我的水晶球目前无法使用。
  • 你在在做什么 你的代码是什么样的?您能否提供给我们Minimal, Complete, and Verifiable Example?
  • 而且这个加密也有问题,因为上面的字符串只显示“kylewbanks.com”,但解密后的数据显示:“kylewbanks.com0”,最后多了0..跨度>
  • 您需要为结尾的 \0 预留空间,例如` char encrypted[strlen(baseStr) + 1];, char decrypted[strlen(baseStr)+1];` 你还需要放置尾随零字节。
  • 请记住,C 中的字符串实际上称为 null terminated 字符串。该终止意味着一串 X 字符需要为 X+1 个字符留出空间以适应终止符。如果没有终止符,所有标准字符串函数都将超出范围,您将有 未定义的行为。

标签: c encryption visual-studio-2017 xor


【解决方案1】:

MSVC 不支持可变长度数组。一种方法是分配内存。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void encryptDecrypt(char *input, char *output) {
    char key[] = {'K', 'C', 'Q'}; //Can be any chars, and any size array
    size_t i;
    for(i = 0; i < strlen(input); i++) {
        output[i] = input[i] ^ key[i % (sizeof(key)/sizeof(char))];
    }
    output[i] = '\0';               // terminate
}

int main () {
    char baseStr[] = "kylewbanks.com";
    size_t len = strlen(baseStr) + 1;

    char *encrypted = malloc(len);
    if(encrypted == NULL) {
        // error handling
    }
    encryptDecrypt(baseStr, encrypted);
    printf("Encrypted:%s\n", encrypted);

    char *decrypted = malloc(len);
    if(decrypted == NULL) {
        // error handling
    }
    encryptDecrypt(encrypted, decrypted);
    printf("Decrypted:%s\n", decrypted);

    free(decrypted);
    free(encrypted);
}

请注意,字符串终止符需要一个额外的字节 - 并且字符串应该被终止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2019-08-17
    • 1970-01-01
    • 2021-02-25
    • 2018-04-08
    • 2017-04-27
    • 2018-03-16
    相关资源
    最近更新 更多