From c1d838322668dc707ceff3dfec987c97389255d7 Mon Sep 17 00:00:00 2001 From: Andrew Bettison Date: Thu, 13 Nov 2014 10:01:08 +1030 Subject: [PATCH] Add strn_digest_passphrase() Uses SHA512 internally --- sourcefiles.mk | 2 +- str.c | 19 +++++++++++++++++++ str.h | 12 ++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/sourcefiles.mk b/sourcefiles.mk index a1d58d60..08a89452 100644 --- a/sourcefiles.mk +++ b/sourcefiles.mk @@ -26,6 +26,7 @@ SERVAL_CLIENT_SOURCES = \ strbuf_helpers.c \ str.c \ strlcpy.c \ + sha2.c \ uuid.c \ whence.c \ xprintf.c @@ -96,7 +97,6 @@ SERVAL_DAEMON_SOURCES = \ rhizome_sync.c \ serval_packetvisualise.c \ server.c \ - sha2.c \ vomp.c \ vomp_console.c \ fec-3.0.1/ccsds_tables.c \ diff --git a/str.c b/str.c index e235b8ec..811bb062 100644 --- a/str.c +++ b/str.c @@ -21,6 +21,7 @@ #include "str.h" #include "strbuf_helpers.h" #include "constants.h" +#include "sha2.h" #include #include @@ -975,6 +976,24 @@ size_t strn_fromprint(unsigned char *dst, size_t dstsiz, const char *src, size_t return dst - odst; } +void str_digest_passphrase(unsigned char *dstBinary, size_t dstlen, const char *passphrase) +{ + return strn_digest_passphrase(dstBinary, dstlen, passphrase, strlen(passphrase)); +} + +void strn_digest_passphrase(unsigned char *dstBinary, size_t dstlen, const char *passphrase, size_t passlen) +{ + assert(dstlen <= SERVAL_PASSPHRASE_DIGEST_MAX_BINARY); + SHA512_CTX context; + static const char salt1[] = "Sago pudding"; + static const char salt2[] = "Rhubarb pie"; + SHA512_Init(&context); + SHA512_Update(&context, (unsigned char *)salt1, sizeof salt1 - 1); + SHA512_Update(&context, (unsigned char *)passphrase, passlen); + SHA512_Update(&context, (unsigned char *)salt2, sizeof salt2 - 1); + SHA512_Final_Len(dstBinary, dstlen, &context); +} + /* Return true if the string resembles a URI. * Based on RFC-3986 generic syntax, assuming nothing about the hierarchical part. * diff --git a/str.h b/str.h index ac5979b3..b51f3e04 100644 --- a/str.h +++ b/str.h @@ -286,6 +286,18 @@ size_t strn_fromprint(unsigned char *dst, size_t dstsiz, const char *src, size_t #define alloca_str_toprint_quoted(str, quotes) toprint_str((char *)alloca(toprint_str_len((str), (quotes)) + 1), -1, (str), (quotes)) #define alloca_str_toprint(str) alloca_str_toprint_quoted(str, "``") +/* -------------------- Pass phrases -------------------- */ + +#define SERVAL_PASSPHRASE_DIGEST_MAX_BINARY 64 + +/* Digest a pass phrase into binary data of at most + * SERVAL_PASSPHRASE_DIGEST_MAX_BINARY bytes using a strong one-way function. + * + * @author Andrew Bettison + */ +void str_digest_passphrase(unsigned char *dstBinary, size_t dstlen, const char *passphrase); +void strn_digest_passphrase(unsigned char *dstBinary, size_t dstlen, const char *passphrase, size_t passlen); + /* -------------------- Useful string primitives -------------------- */ /* Like strchr(3), but only looks for 'c' in the first 'n' characters of 's', stopping at the first