Introduction

In this tutorial, we will check how to apply the SHA1 algorithm to a message using the Arduino core on the ESP8266.

SHA1 is a hash algorithm that produces a message digest with a length of 160 bits (20 bytes) [1].

The tests of this tutorial were performed using a DFRobot’s ESP8266 FireBeetle board.

The code

The first thing we need to do is including the Hash.h library, which will expose the function we need to use the SHA1 algorithm.

#include "Hash.h"

Moving on to the setup function, we will start by opening a serial connection, to later output the message digest.

Serial.begin(115200);

 Now, to apply the SHA1 algorithm to a message, we simply need to call the sha1 function, passing as input the string to which we want to apply the algorithm. As output, this function will return the message digest in hexadecimal format.

String result = sha1("test string");

Note that the sha1 function is overloaded and thus it has many definitions, as can be seen by the header file of the Hash.h library. For example, in one of the function definitions, we can pass as input a 20 bytes data buffer to hold the result of applying the hash algorithm, rather than obtaining it as a hexadecimal string, like we did.

Finally, we will print the result to the serial port.

Serial.println();
Serial.print(result);

The final source code can be seen below.

#include "Hash.h"

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

  String result = sha1("test string");

  Serial.println();
  Serial.print(result);

}

void loop() {}

Testing the code

To test the code, simply compile it and upload it to your ESP266 device. When the procedure finishes, open the Arduino IDE serial monitor. You should get an output similar to figure 1, which shows the message digest in hexadecimal format.

ESP8266 Arduino SHA1 algorithm

                                                 Figure 1 – Output of the program.

You can compare the result obtained on the ESP8266 with the result obtained for the same string using this online tool. As shown in figure 2, the obtained result matches the one from the ESP8266.

SHA1 online tool

                         Figure 2 – Result of applying the SHA1 algorithm, using an online tool.