cmidi cmidi - 22 days ago 7
C Question

Difference between 2 vs "\2"

While trying to implement the IKE session key generation algorithms I came across the following code snippets for the following algorithm implementation
Algorithm for generating a certain session key

SKEYID_e = HMAC (SKEYID, SKEYID_a || gxy || CKY-I || CKY-R || 2)


implementation to get the last concatenation HMAC of digit 2

hmac_update(ctx, (unsigned char *) "\2", 1)


here hmac_update is the API used to concatenate the buffer to get the HMAC before finalizing the digest and CTX is HMAC context "\2" is adding the digit 2 and 1 is size of the buffer.

My question is what is the difference between and escaped
unsigned char *
"\2"
and a
char
/
uint8_t
value
2

Answer

The difference is that a char with numeric value 2 and the string "\2" is that the former is a char and the second is a literal representing a character array containing a char with numeric value 2 and then a char with numeric value 0. In other words:

  • (char)2 is a single character. Its type is char. Its value is 2.
  • "\2" is an array of characters. Its type decays to const char*. Its first entry is 2 and its second entry is 0.

Since hmac_update expects as its second argument a pointer to the bytes to use in the update, you can't provide 2 or (char)2 as an argument, since doing so would try to convert an integer to a pointer (oops). Using "\2" solves this problem by providing a pointer to the byte in question. You could also do something like this:

const char value = 2;
hmac_update(ctx, &value, 1);