How to compare a byte array with a String or char array?

Hello! This is part of the code, regarding this issue:

#include <Crypto.h>             // AES 128 CBC with pkcs7, RNG, SHA256 and SHA256HMAC  
#include <base64.hpp> 
#define HMAC_KEY_LENGTH 16

byte hmacKey[HMAC_KEY_LENGTH] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
byte message[HMAC_KEY_LENGTH] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};

void setup() {
  Serial.begin(115200);
 SHA256HMAC hmac(hmacKey, HMAC_KEY_LENGTH);
    hmac.doUpdate(message, HMAC_KEY_LENGTH);
    byte authCode2[SHA256HMAC_SIZE];
    hmac.doFinal(authCode2);
    
Serial.print("AUTHCODE2 IS : ");
     for (byte i=0; i < SHA256HMAC_SIZE; i++)
  {
      if (authCode2[i]<0x10) {  }
      Serial.print(authCode2[i], HEX); //This prints 9CF3809536BBBC0B3D5536E6247C182BB1DC29C6DDC21D604CFAB92FDF9
  }

  String received = "9CF3809536BBBC0B3D5536E6247C182BB1DC29C6DDC21D604CFAB92FDF9";

  //How to compare?


}

void loop() {
  // put your main code here, to run repeatedly:

}

Basically i want to compare the byte array authCode2 with the string i have called received. I have tried converting the byte array to a String multiple times but it is always wrongly converted. I have tried once to convert the String into a byte array but it also fails when comparing the two of them... Does anyone know of a solution for this?

Thanks

memcmp?

Serial.print(authCode2[i], HEX);
One problem with this approach is that leading zeros are omitted from hex digits when printed.

Better to compare bytes in memory, as suggested above.

You can't directly compare binary bytes to the string of hexadecimal digits.

You could store the constant as binary:

byte received[] = {0x9C, 0xF3, 0x80, 0x95, 0x36, 0xBB, 0xBC, 0x0B, 0x3D, 0x55, 0x36, 0xE6, 0x24, 0x7C, 0x18, 0x2B, 0xB1, 0xDC, 0x29, 0xC6, 0xDD, 0xC2, 0x1D, 0x60, 0x4C, 0xFA, 0xB9, 0x2F, 0xDF, 0x9};

You have an odd number of digits so I suspect a leading 0 has been lost. Try printing out the value as:

  Serial.print("AUTHCODE2 IS : ");
  for (byte i = 0; i < SHA256HMAC_SIZE; i++)
  {
    Serial.print(, "0x");
    Serial.print(authCode2[i], HEX);
  }

Thanks a lot, it makes sense now i wasn't thinking straight about the byte array. It's fixed now :slight_smile:

What EXACTLY are you looking for when you say "compare"? Equal length? All bytes equal? One byte being less than the other?