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

Freedom_Ben
  • 11,247
  • 10
  • 69
  • 89
cmidi
  • 1,880
  • 3
  • 20
  • 35

2 Answers2

6

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);
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
-1

"2" describes the character with the hex code 2 (which is a non-printable character, check http://ascii-table.com/info.php?u=x0002);
The digit "2" has the hex code 0x050 = 50, as is the printable character '2'.

Aganju
  • 6,295
  • 1
  • 12
  • 23
  • 1
    I don't believe this answers the OP's question - they're asking about the difference between "a `char` with numeric value 2` and `"\2"`, not about the difference between "the character `'2'`" and "the character `'\2'`." – templatetypedef Nov 17 '16 at 19:07