Skip to content

Commit 38b0778

Browse files
committed
Remove some duplicated code
1 parent 30b08d6 commit 38b0778

File tree

2 files changed

+6
-20
lines changed

2 files changed

+6
-20
lines changed

libraries/WebServer/examples/HttpBasicAuthSHA1orBearerToken/HttpBasicAuthSHA1orBearerToken.ino

+4-14
Original file line numberDiff line numberDiff line change
@@ -80,21 +80,11 @@ void setup() {
8080
}
8181
ArduinoOTA.begin();
8282

83-
8483
// Convert token to a convenient binary representation.
8584
//
86-
if (secret_token_hex.length() != 2 * 20) {
87-
Serial.println("Bearer token does not look like a hex string ?!");
88-
}
89-
90-
#define _H2D(x) (((x)>='0' && ((x) <='9')) ? ((x)-'0') : (((x)>='a' && (x)<='f') ? ((x)-'a'+10) : 0))
91-
#define H2D(x) (_H2D(tolower((x))))
92-
const char * _shaBase64 = secret_token_hex.c_str();
93-
for (int i = 0; i < 20; i++) {
94-
unsigned char c = _shaBase64[2 * i + 0];
95-
unsigned char d = _shaBase64[2 * i + 1];
96-
_bearer[i] = (H2D(c) << 4) | H2D(d);
97-
};
85+
size_t len = HEXBuilder::hex2bytes(_bearer,sizeof(_bearer),secret_token_hex);
86+
if (len != 20)
87+
Serial.println("Bearer token does not look like a valid SHA1 hex string ?!");
9888

9989
server.on("/", []() {
10090
if (!server.authenticate(&check_bearer_or_auth)) {
@@ -116,4 +106,4 @@ void loop() {
116106
ArduinoOTA.handle();
117107
server.handleClient();
118108
delay(2);//allow the cpu to switch to other tasks
119-
}
109+
}

libraries/WebServer/src/WebServer.cpp

+2-6
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include "WiFiServer.h"
2929
#include "WiFiClient.h"
3030
#include "WebServer.h"
31+
#include "HEXBuilder.h"
3132
#include "FS.h"
3233
#include "detail/RequestHandlersImpl.h"
3334
#include "mbedtls/md5.h"
@@ -164,12 +165,7 @@ bool WebServer::authenticateBasicSHA1(const char * _username, const char * _sha1
164165
#define _H2D(x) (((x)>='0' && ((x) <='9')) ? ((x)-'0') : (((x)>='a' && (x)<='f') ? ((x)-'a'+10) : 0))
165166
#define H2D(x) (_H2D(tolower((x))))
166167
if (strlen(_sha1Base64orHex) == 20 * 2) {
167-
for(int i = 0; i < 20; i++) {
168-
unsigned char c = _sha1Base64orHex[2*i];
169-
unsigned char d = _sha1Base64orHex[2*i+1];
170-
sha1calc[i] = (H2D(c)<<4) | H2D(d);
171-
};
172-
ret = 0;
168+
HEXBuilder::bytes2hex(sha1calc,sizeof(sha1calc),sha1,sizeof(sha1));
173169
} else
174170
ret = mbedtls_base64_encode((uint8_t*)sha1calc, sizeof(sha1calc), &olen, sha1, sizeof(sha1));
175171

0 commit comments

Comments
 (0)