commit 2e1d543685a517d0fa26a843f8786ff425e2bedc
parent 8664e65cc612df2f83a431f2b6cb5337b5e54ca1
Author: Nihal Jere <nihal@nihaljere.xyz>
Date: Sat, 20 Feb 2021 20:00:30 -0600
sha256.*: add sha256_tostr and sha256_fromstr
Diffstat:
2 files changed, 46 insertions(+), 0 deletions(-)
diff --git a/sha256.c b/sha256.c
@@ -152,3 +152,45 @@ sha256_update(void *ctx, const void *m, unsigned long len)
processblock(s, p);
memcpy(s->buf, p, len);
}
+
+/* dest should be 32 bytes, src should be 64 + \0 */
+int
+sha256_fromstr(char *dest, const char *src)
+{
+ unsigned char msn, lsn;
+
+ if (dest == NULL || src == NULL) {
+ return -1;
+ }
+
+ for (int i = 0; i < 32; i++) {
+ msn = src[2*i];
+ lsn = src[2*i+1];
+
+ dest[i] = (isdigit(lsn) ? (lsn - '0') : (lsn - 'a' + 10))
+ + ((isdigit(msn) ? (msn - '0') : (msn - 'a' + 10)) << 4);
+ }
+
+ return 0;
+}
+
+/* dest should be 65 bytes, src should be 32 */
+int
+sha256_tostr(char *dest, const char *src)
+{
+ unsigned char msn, lsn;
+
+ if (dest == NULL || src == NULL) {
+ return -1;
+ }
+
+ for (int i = 0; i < 32; i++) {
+ msn = (src[i] >> 4) & 0xF;
+ lsn = src[i] & 0xF;
+
+ dest[2*i] = (0 <= msn && msn < 10) ? (msn + '0') : (msn + 'a' - 10);
+ dest[2*i+1] = (0 <= lsn && lsn < 10) ? (lsn + '0') : (lsn + 'a' - 10);
+ }
+
+ return dest[64] = '\0';
+}
diff --git a/sha256.h b/sha256.h
@@ -16,3 +16,7 @@ void sha256_update(void *ctx, const void *m, unsigned long len);
/* state is ruined after sum, keep a copy if multiple sum is needed */
/* part of the message might be left in s, zero it if secrecy is needed */
void sha256_sum(void *ctx, uint8_t md[SHA256_DIGEST_LENGTH]);
+/* convert hex string to 32 byte array */
+int sha256_fromstr(char *dest, const char *src);
+/* convert 32 byte array to hex string */
+int sha256_tostr(char *dest, const char *src);