传递参数时出错,并将其转换为十六进制

Error when passing arguments and convert it to hexadecimal

本文关键字:转换 十六进制 参数 出错      更新时间:2023-10-16

如何通过参数插入文本并自动将其转换为十六进制?

I tried with:

unsigned char aesKey[32] = argv[1];

but get errors

输出如下所示:

unsigned char aesKey[32] = {
    0x53, 0x28, 0x40, 0x6e, 0x2f, 0x64, 0x63, 0x5d, 0x2d, 0x61, 0x77, 0x40, 0x76, 0x71, 0x77, 0x28, 
    0x74, 0x61, 0x7d, 0x66, 0x61, 0x73, 0x3b, 0x5d, 0x66, 0x6d, 0x3c, 0x3f, 0x7b, 0x66, 0x72, 0x36
};
unsigned char *buf;
aes256_context ctx;
aes256_init(&ctx, aesKey);
for (unsigned long i = 0; i < lSize/16; i++) {
    buf = text + (i * 16);
    aes256_encrypt_ecb(&ctx, buf);
}
aes256_done(&ctx);

Thanks in advance

在C和c++中,当你有像

这样的代码时
char name[]="John Smith";

编译器在编译时知道该char数组的大小,以及所有值的大小。因此,它可以在堆栈帧上分配它并为其赋值。

当你有类似的代码时Char * STRPTR = foo();Char str[] = str;

编译器不知道strptr所指向的字符串的大小和值是多少。这就是为什么这在C/c++中是不允许的。

换句话说,只能将字符串字面值赋值给字符数组,而且也只能在声明时赋值。

char name[] = "John Smith";

是被允许的。

char name[32];
name = "John Smith";

使用memcpy

所以你可以使用内存。(或者使用其他人提到的c++替代品)

unsigned char *aesKey;
size_t len = (strlen(argv[1])+1)*sizeof(unsigned char);
aesKey = malloc(len);
memcpy(aesKey, argv[1], len);

旧方案

(这是我之前的答案,上面的答案更好)所以你需要使用strong。

unsigned char aesKey[32];
strncpy((char *) aesKey, argv[1], 32);

注意这个例程是强的而不是强的。策略是不安全的。(感谢PRouleau的arg修复)

如果strncpy在Visual Studio中不可用,那么你可能不得不尝试strcpy_s(感谢Google: user:427390)

在C/c++中,编译器不会自动操作数组。你必须指定如何复制它们。

旧的好方法是使用memcpy()。更现代的方法是使用std::copy()。在任何情况下,你必须在复制到aesKey之前验证argv[1]的长度。

要转换为十六进制,您可能必须将像"AAEE3311"这样的字符串(最多2*32个字符)转换为字节。您应该使用std::istringstream并逐个填充aesKey位置。

,

std::istringstream Input(argv[1]);
Input >> std::hex >> aesKey[0];

我想象一个程序是这样被调用的——

myprog 0x53 0x28 0x40 0x6e 0x2f 0x64 0x63

在程序内部,我将有一个循环将参数赋值给数组-

const int size = 32;
unsigned char aesKey[size];
char* p;
for (int i = 1; i < argc || i < size; ++i)
{
    aesKey[i] = (unsigned char)strtol(argv[i], &p, 16);
}