1 c encryption xor visual-studio-2017
所以我想在写入.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.
Run Code Online (Sandbox Code Playgroud)
但是,当我开始使用Visual Studio 2017时,它显示以下错误:
Error (active) E0059 function call is not allowed in a constant expression
Run Code Online (Sandbox Code Playgroud)
这意味着在声明数组时我无法放置变量,所以我的加密方法是否适用于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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,字符串终止符需要一个额外的字节 - 字符串应该终止.