Skip to content

Commit 1629623

Browse files
authored
refactor: use std::snprintf for SHA hex formatting
2 parents 5b855a2 + d0f8526 commit 1629623

3 files changed

Lines changed: 7 additions & 4 deletions

File tree

‎sha1.cpp‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@
1818
/* Based on: http://www.zedwood.com/article/cpp-sha1-function
1919
* Modified by NewYaroslav, 2025-04-15
2020
*/
21-
21+
22+
#include <cstdio>
2223
#include <algorithm>
2324
#include "sha1.hpp"
2425

@@ -247,7 +248,7 @@ namespace hmac_hash {
247248
char buf[2 * hmac_hash::SHA1::DIGEST_SIZE + 1];
248249
std::fill(buf, buf + (2 * hmac_hash::SHA1::DIGEST_SIZE + 1), '\0');
249250
for(size_t i = 0; i < hmac_hash::SHA1::DIGEST_SIZE; ++i) {
250-
sprintf(buf + i * 2, "%02x", digest[i]);
251+
std::snprintf(buf + i * 2, sizeof(buf) - i * 2, "%02x", digest[i]);
251252
}
252253
return std::string(buf, (2 * hmac_hash::SHA1::DIGEST_SIZE));
253254
}

‎sha256.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141

4242
#include <algorithm>
4343
#include <cstring>
44+
#include <cstdio>
4445
//#include <fstream>
4546
#include "sha256.hpp"
4647

@@ -206,7 +207,7 @@ namespace hmac_hash {
206207
char buf[2 * hmac_hash::SHA256::DIGEST_SIZE + 1];
207208
std::fill(buf, buf + (2 * hmac_hash::SHA256::DIGEST_SIZE + 1), '\0');
208209
for(size_t i = 0; i < hmac_hash::SHA256::DIGEST_SIZE; ++i) {
209-
sprintf(buf + i * 2, "%02x", digest[i]);
210+
std::snprintf(buf + i * 2, sizeof(buf) - i * 2, "%02x", digest[i]);
210211
}
211212
return std::string(buf, (2 * hmac_hash::SHA256::DIGEST_SIZE));
212213
}

‎sha512.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141

4242
#include <algorithm>
4343
#include <cstring>
44+
#include <cstdio>
4445
#include "sha512.hpp"
4546

4647
#define SHA2_SHFR(x, n) (x >> n)
@@ -241,7 +242,7 @@ namespace hmac_hash {
241242
char buf[2 * hmac_hash::SHA512::DIGEST_SIZE + 1];
242243
std::fill(buf, buf + (2 * hmac_hash::SHA512::DIGEST_SIZE + 1), '\0');
243244
for(size_t i = 0; i < hmac_hash::SHA512::DIGEST_SIZE; ++i){
244-
sprintf(buf + i * 2, "%02x", digest[i]);
245+
std::snprintf(buf + i * 2, sizeof(buf) - i * 2, "%02x", digest[i]);
245246
}
246247
return std::string(buf, (2 * hmac_hash::SHA512::DIGEST_SIZE));
247248
}

0 commit comments

Comments
 (0)