简体   繁体   中英

Converting unsigned char to hex incorrect. Last value will always increase + 1

I have issue that i cant figure out why.

uint8_t nonce[17] = "1234567890123456";
String cipherText = String();
for (int i = 0; i < 16; i++) {
     char str[3];
     sprintf(str, "%02X", nonce[i]);
     cipherText = cipherText+String(str);
}
System.println(cipherText);

result is: "31323334353637383930313233343537"

when i use hex converter online to decode back, the string result is "1234567890123457" which is not the same as the the initial chars. using bytes {0x01}, {0x02}.. with the same result.

this code was a part that pass as a iv to a cipher encryption. hex converter online: https://string-functions.com/hex-string.aspx

The last value will always increase + 1. I have tried other approach to loop with the same result. I also have use to convert the unsigned char to base64 and decode and have the same issue. Anyone can help whats wrong with this codes?

figure out that the library that was used modifies the unsigned char that was pass to it. I have to use a copy of the var to have the correct HEX value other then the one i use to pass to the lib.

it was mentioned by the user chegewara in the git example here: here

static void cbc()
{
#if defined(MBEDTLS_CIPHER_MODE_CBC)
    unsigned char iv[] = {0xff, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
    unsigned char iv1[] = {0xff, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
    unsigned char encrypt_output[INPUT_LENGTH] = {0};
    unsigned char decrypt_output[INPUT_LENGTH] = {0};
    mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_ENCRYPT, INPUT_LENGTH, iv, input, encrypt_output);
    mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, INPUT_LENGTH, iv1, encrypt_output, decrypt_output);
    ESP_LOG_BUFFER_HEX("cbc", encrypt_output, INPUT_LENGTH);
    ESP_LOG_BUFFER_HEX("cbc", decrypt_output, INPUT_LENGTH);
    ESP_LOGI("cbc", "%s", decrypt_output);
#endif
}

"Im guessing you made common mistake, which i did when i made that example too. Then IV is changed during encryption/decryption by code, which means you cant use the same char array to do both in the same code. Best way is to keep 1 copy as const char array, then before encrypt/decrypt copy it into arrays used in process." - chegewara

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM