SensESP 3.1.1
Universal Signal K sensor toolkit ESP32
Loading...
Searching...
No Matches
hash.cpp
Go to the documentation of this file.
1#include "hash.h"
2
3#include "esp_arduino_version.h"
4
5#include "mbedtls/base64.h"
6#include "mbedtls/md.h"
7#include "mbedtls/md5.h"
8
9namespace sensesp {
10
19void Sha1(const String& payload_str, uint8_t *hash_output) {
20 const char *payload = payload_str.c_str();
21
22 const int size = 20;
23
24 mbedtls_md_context_t ctx;
25 mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
26
27 const size_t payload_length = payload_str.length();
28
29 mbedtls_md_init(&ctx);
30 mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0);
31 mbedtls_md_starts(&ctx);
32 mbedtls_md_update(&ctx, reinterpret_cast<const unsigned char *>(payload),
33 payload_length);
34 mbedtls_md_finish(&ctx, hash_output);
35 mbedtls_md_free(&ctx);
36}
37
45String MD5(const String& payload_str) {
46 const char *payload = payload_str.c_str();
47 char output[33] = {0};
48
49 const size_t payload_length = payload_str.length();
50
51 mbedtls_md5_context ctx_;
52 uint8_t i;
53 uint8_t buf_[16] = {0};
54 mbedtls_md5_init(&ctx_);
55#if ESP_ARDUINO_VERSION_MAJOR > 2
56 mbedtls_md5_starts(&ctx_);
57 mbedtls_md5_update(&ctx_, (const uint8_t *)payload, payload_length);
58 mbedtls_md5_finish(&ctx_, buf_);
59#else
60 mbedtls_md5_starts_ret(&ctx_);
61 mbedtls_md5_update_ret(&ctx_, (const uint8_t *)payload, payload_length);
62 mbedtls_md5_finish_ret(&ctx_, buf_);
63#endif
64 mbedtls_md5_free(&ctx_);
65 for (i = 0; i < 16; i++) {
66 sprintf(output + (i * 2), "%02x", buf_[i]);
67 }
68 return String(output);
69}
70
80String Base64Sha1(const String& payload_str) {
81 uint8_t hash_output[20];
82
83 uint8_t encoded[32];
84
85 size_t output_length;
86
87 sensesp::Sha1(payload_str, hash_output);
88
89 int retval = mbedtls_base64_encode(encoded, sizeof(encoded), &output_length,
90 hash_output, 20);
91
92 if (retval != 0) {
93 ESP_LOGE(__FILENAME__, "Base64 encoding failed");
94 return "";
95 }
96
97 String encoded_str((char *)encoded);
98
99 encoded_str.replace("/", "_");
100
101 return encoded_str;
102}
103
104} // namespace sensesp
void Sha1(const String &payload_str, uint8_t *hash_output)
SHA-1 hash function.
Definition hash.cpp:19
String MD5(const String &payload_str)
MD5 hash function.
Definition hash.cpp:45
String Base64Sha1(const String &payload_str)
A base64-encoded SHA-1 hash function.
Definition hash.cpp:80