Uno R4 Wifi - HMAC 256 library

Hi Folks,

I'm looking for an SHA library that is compatible with the Uno R4 Wifi - I've tried a few, but keep getting AVR/io.h not found or the code is out of date and no longer works.

Some of the documentation says the board is not an AVR board.

The reason I ask is that this being the 21st century, just about everything requires a certificate - and in this case I am connecting to Azure.

Regards.

One of the first search results: GitHub - intrbiz/arduino-crypto: A minimal crypto library for ESP8266 Arduino.

It says ESP8266 but a quick glance at the source code makes me think that it will work with other boards.

If a code is old does not mean that it is bad code; there is no need to update code if it is working.

Search: arduino sha256 at DuckDuckGo

Thanks, I'll take a look at it.

I didn't get very far.

Apart from the warning (and it is only a warning): WARNING: library Crypto claims to run on esp8266, esp32 architecture(s) and may be incompatible with your current board which runs on renesas_uno architecture(s).

I got an error on RNG::fill which I am yet to find a copy of that actually works.

The closest I have come to is here: Arduino Cryptography Library: Generating random numbers

Although why the authors decided no-one would want to download anything I know not.

The ultimate goal is to connect to Azure using MQTT, so I suspect this may not work anyhow as I can't see how Azure would know how to do the decryption (given this code does not work with keys).

What error?

The random fill just fills a memory area with zeroes when using a non-ESP board. Else it fills with random numbers.

I do not know too much about about encryption but filling with zeroes results in a predictable encryption which is considered undesired.

Depending on how strong your random number generator needs to be it can be reasonably easy to modify that function; just call random() form RNG::get().

byte RNG::get()
{
#if defined ESP32
    // ESP32 only
    uint32_t* randReg = (uint32_t*) 0x3FF75144;
    return (byte) *randReg;
#elif defined ESP8266
    // ESP8266 only
    uint32_t* randReg = (uint32_t*) 0x3FF20E44L;
    return (byte) *randReg;
#else
    // NOT SUPPORTED
// sterretje 20251016
    return random();
#endif
}

Now that is still not too random; you might want to seed the random number generator with some unpredictable number. If your application uses user input you can use the first time that something happened (e.g. serial received, button pressed) and store that in EEPROM (not sure what the Uno R4 WiFi exactly has, it might be simulated EEPROM). That saved time can be used the next time that want to seed the random number generator.

And there is this topic on the forum: The reliable but not very sexy way to seed random (latest code in post #53). You will need to hack it a bit because it was written for boards with an AVR procssor (including avr/eeprom.h), not a Renesas.

You need an application in Azure that can do the decryption and just like you have SHA256 keys in your Arduino you will have the same SHA256 keys in the Azure application.

But this does not have anything to do with certificates. The certificates are used for the encryption of the communication (e.g. https).

I have no idea how an Uno R4 WiFi works when it comes to network / WiFi communication. Maybe https://docs.arduino.cc/tutorials/uno-r4-wifi/wifi-examples/ shines some light on it for you.

Thanks all, I orderd an MKR Wifi 1010 as it claims compatibility with the Azure IoT library - can't have too many devices.

I'm trying to connect to the Azure IoT hub using MQTT - easy to do in C# as one can use the connection string, only a couple of lines.

However, the issue on the Nano R4 (apart from not so much support) was encryption.

The sas token needs to be constructed in a certain way with part of it being encoded as hmac-sha256.

Following is some JavaScript that I am trying to reproduce.

 var hmac = crypto.createHmac('sha256', Buffer.from(signingKey, 'base64'));
 hmac.update(toSign);
 var base64UriEncoded = encodeURIComponent(hmac.digest('base64'));

SigningKey is my input key, and toSign is the string needed to be signed.

It may not matter, but you initially said Uno R4, but mostly recently Nano R4. Which do you have?

Uno R4 has a Software Secure Element that does SHA256. So you can therefore do HMAC-SHA256 with "a little bit" of code. While putting this together

#include <SoftwareATSE.h>  // Software "AT" Secure Element

class Hasher {
public:
  virtual size_t blockSize() const = 0;
  virtual size_t lengthOut() const = 0;
  virtual bool hash(uint8_t *digest, const uint8_t *message, size_t length) = 0;
};

class SHA256 : public Hasher {
  static constexpr size_t SHA256_BLOCK = 64;
  static constexpr size_t SHA256_LEN = 32;
public:
  size_t blockSize() const override {
    return SHA256_BLOCK;
  }
  size_t lengthOut() const override {
    return SHA256_LEN;
  }
  bool hash(uint8_t *digest, const uint8_t *message, size_t length) override {
    return SATSE.SHA256(message, length, digest);
  }
} h256;

class HMAC {
  Hasher &h;
  uint8_t *key;
  void blockSizedKey(const uint8_t *secretKey, size_t keyLength) {
    key = new uint8_t[h.blockSize()];
    if (!key) {
      return;
    }
    size_t i;
    if (keyLength > h.blockSize()) {
      h.hash(key, secretKey, keyLength);
      i = h.lengthOut();
    } else {
      memcpy(key, secretKey, keyLength);
      i = keyLength;
    }
    while (i < h.blockSize()) {
      key[i++] = 0;
    }
  }
  void keyPad(uint8_t *pad, uint8_t value) {
    for (size_t i = 0; i < h.blockSize(); i++) {
      pad[i] = key[i] ^ value;
    }
  }
public:
  HMAC(Hasher &hasher, const uint8_t *secretKey, size_t keyLength) : h(hasher) {
    blockSizedKey(secretKey, keyLength);
  }
  ~HMAC() {
    if (key) delete[] key;
  }
  bool compute(uint8_t *digest, const uint8_t *message, size_t length) {
    if (!key) {
      return false;
    }
    uint8_t inner[h.blockSize()];
    uint8_t outer[h.blockSize() + h.lengthOut()];

    keyPad(inner, 0x36);
    keyPad(outer, 0x5c);

    size_t bufLen = h.blockSize() + length;
    auto buf = new uint8_t[bufLen];
    if (!buf) {
      return false;
    }
    memcpy(buf, inner, h.blockSize());
    memcpy(buf + h.blockSize(), message, length);

    if (!h.hash(outer + h.blockSize(), buf, bufLen)) {
      delete[] buf;
      return false;
    }
    delete[] buf;
    return h.hash(digest, outer, h.blockSize() + h.lengthOut());
  }
};

void printBufferHex(const byte *input, size_t inputLength) {
  for (size_t i = 0; i < inputLength; i++) {
    if (i && i % 8 == 0) {
      Serial.print(i & 8 ? " " : "\r\n");
    }
    Serial.print(input[i] >> 4, HEX);
    Serial.print(input[i] & 0x0f, HEX);
  }
  Serial.println();
}


String key;

void setup() {
  Serial.begin(115200);

  // Important to see some of these startup messages, so wait to go
  while (!Serial.available()) {
    if (millis() % 1500 == 0) {
      Serial.println("\n^^ press Enter to start");
      delay(1);
    }
  }
  Serial.readStringUntil('\n');

  if (!SATSE.begin()) {
    Serial.println("Failed to communicate with Software Secure Element!");
    Serial.println("Make sure your WiFi firmware version is greater than 0.3.0");
    for (;;);
  }

  while (!key.length()) {
    Serial.println("^^ Enter secret shared key ^^");
    while (!Serial.available()) delay(1);
    key = Serial.readStringUntil('\n');
    key.trim();
  }
  Serial.print("key length: ");
  Serial.println(key.length());
}

void loop() {
  static bool prompt = true;
  if (prompt) {
    prompt = false;
    Serial.println("^^ Enter message to sign ^^");
  }

  if (!Serial.available()) {
    return;
  }
  prompt = true;

  String message = Serial.readStringUntil('\n');
  message.trim();
  Serial.print("signing: \"");
  Serial.print(message);
  Serial.println('"');

  HMAC hmac(h256, reinterpret_cast<const uint8_t*>(key.c_str()), key.length());
  uint8_t sig[h256.lengthOut()];
  if (hmac.compute(sig, reinterpret_cast<const uint8_t*>(message.c_str()), message.length())) {
    Serial.println("HMAC done");
    printBufferHex(sig, h256.lengthOut());
  } else {
    Serial.println("HMAC failed");
  }
}

it seems that the underlying MbedTLS does not allow the literal word "secret" as the key for the HMAC; the SATSE.SHA256 call fails. It's a horrible choice anyway, but still.

Equivalent JavaScript, taking a key in whatever form is convenient, and printing the results in hex for comparison

const crypto = require('node:crypto');
const h256 = (key, message) => {
  const hmac = crypto.createHmac('sha256', key);
  hmac.update(message);
  return hmac.digest('hex');
};

prints

> h256('papaya', 'hello')
'6dd944cd627be304c73aad1f6833eb41e7ba205872c1f11804a3379c3aeb945e'

The sketch above, with the same six-letter fruit key

^^ press Enter to start
^^ Enter secret shared key ^^
key length: 6
^^ Enter message to sign ^^
signing: "hello"
HMAC done
6DD944CD627BE304 C73AAD1F6833EB41
E7BA205872C1F118 04A3379C3AEB945E

Having said all that, instead of a SAS token, apparently you can use a client cert with Azure IoT (just like with AWS). I posted in a thread a few days ago about getting mTLS on Uno R4 to work with Mosquitto.