SensESP 3.0.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 "mbedtls/base64.h"
4#include "mbedtls/md.h"
5#include "mbedtls/md5.h"
6
7namespace sensesp {
8
17void Sha1(const String& payload_str, uint8_t *hash_output) {
18 const char *payload = payload_str.c_str();
19
20 const int size = 20;
21
22 mbedtls_md_context_t ctx;
23 mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
24
25 const size_t payload_length = payload_str.length();
26
27 mbedtls_md_init(&ctx);
28 mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0);
29 mbedtls_md_starts(&ctx);
30 mbedtls_md_update(&ctx, reinterpret_cast<const unsigned char *>(payload),
31 payload_length);
32 mbedtls_md_finish(&ctx, hash_output);
33 mbedtls_md_free(&ctx);
34}
35
43String MD5(const String& payload_str) {
44 const char *payload = payload_str.c_str();
45 char output[33] = {0};
46
47 const size_t payload_length = payload_str.length();
48
49 mbedtls_md5_context ctx_;
50 uint8_t i;
51 uint8_t buf_[16] = {0};
52 mbedtls_md5_init(&ctx_);
53 mbedtls_md5_starts_ret(&ctx_);
54 mbedtls_md5_update_ret(&ctx_, (const uint8_t *)payload, payload_length);
55 mbedtls_md5_finish_ret(&ctx_, buf_);
56 mbedtls_md5_free(&ctx_);
57 for (i = 0; i < 16; i++) {
58 sprintf(output + (i * 2), "%02x", buf_[i]);
59 }
60 return String(output);
61}
62
72String Base64Sha1(const String& payload_str) {
73 uint8_t hash_output[20];
74
75 uint8_t encoded[32];
76
77 size_t output_length;
78
79 sensesp::Sha1(payload_str, hash_output);
80
81 int retval = mbedtls_base64_encode(encoded, sizeof(encoded), &output_length,
82 hash_output, 20);
83
84 if (retval != 0) {
85 ESP_LOGE(__FILENAME__, "Base64 encoding failed");
86 return "";
87 }
88
89 String encoded_str((char *)encoded);
90
91 encoded_str.replace("/", "_");
92
93 return encoded_str;
94}
95
96} // namespace sensesp
void Sha1(const String &payload_str, uint8_t *hash_output)
SHA-1 hash function.
Definition hash.cpp:17
String MD5(const String &payload_str)
MD5 hash function.
Definition hash.cpp:43
String Base64Sha1(const String &payload_str)
A base64-encoded SHA-1 hash function.
Definition hash.cpp:72