Home » Using SHA-256 with an ESP32

Using SHA-256 with an ESP32

by shedboy71

In this example we will look at how you can generate the hash of a string using the SHA-256 algorithm. We will use the Arduino IDE in which the ESP32 core by luck has a builtin mbed TLS libraries.

If you want to ready more about SHA-2 then start at https://en.wikipedia.org/wiki/SHA-2 and read through this, its a nice introduction

Code

[cpp]

#include “mbedtls/md.h”

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

char *payload = “Hello SHA 256 from ESP32learning”;
byte shaResult[32];

mbedtls_md_context_t ctx;
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256;

const size_t payloadLength = strlen(payload);

mbedtls_md_init(&ctx);
mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0);
mbedtls_md_starts(&ctx);
mbedtls_md_update(&ctx, (const unsigned char *) payload, payloadLength);
mbedtls_md_finish(&ctx, shaResult);
mbedtls_md_free(&ctx);

Serial.print(“Hash: “);

for(int i= 0; i< sizeof(shaResult); i++)
{
char str[3];
sprintf(str, “%02x”, (int)shaResult[i]);
Serial.print(str);
}
}

void loop()
{
}

[/cpp]

Testing

Open the serial monitor window , press the reset button on your board and you should see something like this

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
ets Jun 8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0x00
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0008,len:8
load:0x3fff0010,len:160
load:0x40078000,len:10632
load:0x40080000,len:252
entry 0x40080034
Hash: 2fd33178d3f9a3da6bf046d097cada788bbbb74e5fa2c430dc0e8d24bf3fa6ac

The key thing is the hash, you then need to locate a sha256 hash generator tool on the internet and double check the hash above is correct. i will use the one at https://passwordsgenerator.net/sha256-hash-generator/ mainly because I could screen capture the text and the output

You can see my results here

 

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.