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

时间:2013-01-12 05:17:46

标签: c++ visual-c++

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

我尝试过:

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

但得到错误

输出如下:

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);

提前致谢

3 个答案:

答案 0 :(得分:1)

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

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

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

当你有像这样的代码     char * strptr = foo();     char str [] = strptr;

编译器不知道strptr指向的字符串的大小和值是什么。这就是C / C ++中不允许这样做的原因。

换句话说,只有字符串文字可以分配给char数组,而且只能在声明时分配。

所以

char name[] = "John Smith";

是允许的。

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

是不允许的。

使用memcpy

所以你可以使用memcpy。 (或者使用其他人提到的c ++替代方案)

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

旧解决方案

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

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

注意例程是strncpy而不是strcpy。 strcpy是不安全的。 (感谢PRouleau的arg修复)

如果Visual Studio中没有strncpy,那么您可能需要尝试strcpy_s(感谢Google:用户:427390)

答案 1 :(得分:0)

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

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

对于转换为十六进制,您可能必须将类似“AAEE3311”(最多2 * 32个字符)的字符串转换为字节。您应该使用std :: istringstream并按位置填充您的aesKey位置。

例如:

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

答案 2 :(得分: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);
}