簡體   English   中英

傳遞參數並將其轉換為十六進制時出錯

[英]Error when passing arguments and convert it to hexadecimal

如何通過參數插入文本並將其自動轉換為十六進制?

我嘗試過:

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

提前致謝

在C和C ++中,當您有類似

char name[]="John Smith";

編譯器會在編譯時知道該char數組的大小以及所有值。 因此,它可以在堆棧幀上分配它並為其分配值。

當您擁有char * strptr = foo();這樣的代碼時 char str [] = strptr;

編譯器不知道strptr指向的字符串的大小和值是什么。 這就是為什么在C / C ++中不允許這樣做。

換句話說,只能將字符串文字分配給char數組,也只能在聲明時將其分配給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修復程序)

如果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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM