diff --git a/common/Makefile b/common/Makefile index d5a920730..9c24168f3 100644 --- a/common/Makefile +++ b/common/Makefile @@ -25,6 +25,7 @@ COMMON_SRC_NOGEN := \ common/gossip_rcvd_filter.c \ common/gossip_store.c \ common/hash_u5.c \ + common/hmac.c \ common/htlc_state.c \ common/htlc_trim.c \ common/htlc_tx.c \ diff --git a/common/hmac.c b/common/hmac.c new file mode 100644 index 000000000..6c42fab5d --- /dev/null +++ b/common/hmac.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include + +void hmac(const void *src, size_t slen, + const void *key, size_t klen, + struct hmac *hmac) +{ + crypto_auth_hmacsha256_state state; + + crypto_auth_hmacsha256_init(&state, memcheck(key, klen), klen); + crypto_auth_hmacsha256_update(&state, memcheck(src, slen), slen); + crypto_auth_hmacsha256_final(&state, hmac->bytes); +} + +void subkey_from_hmac(const char *prefix, + const struct secret *base, + struct secret *key) +{ + struct hmac h; + hmac(base->data, sizeof(base->data), prefix, strlen(prefix), &h); + BUILD_ASSERT(sizeof(h.bytes) == sizeof(key->data)); + memcpy(key->data, h.bytes, sizeof(key->data)); +} + +void towire_hmac(u8 **pptr, const struct hmac *hmac) +{ + towire_u8_array(pptr, hmac->bytes, ARRAY_SIZE(hmac->bytes)); +} + +void fromwire_hmac(const u8 **ptr, size_t *max, struct hmac *hmac) +{ + fromwire_u8_array(ptr, max, hmac->bytes, ARRAY_SIZE(hmac->bytes)); +} diff --git a/common/hmac.h b/common/hmac.h new file mode 100644 index 000000000..67456c2e7 --- /dev/null +++ b/common/hmac.h @@ -0,0 +1,30 @@ +#ifndef LIGHTNING_COMMON_HMAC_H +#define LIGHTNING_COMMON_HMAC_H +#include "config.h" +#include +#include +#include + +struct secret; + +/* HMAC used by Sphinx: SHA256 */ +struct hmac { + u8 bytes[crypto_auth_hmacsha256_BYTES]; +}; + +void hmac(const void *src, size_t slen, + const void *key, size_t klen, + struct hmac *hmac); + +/* Common style: hmac to derive key using fixed string prefix. */ +void subkey_from_hmac(const char *prefix, + const struct secret *base, + struct secret *key); + +void towire_hmac(u8 **pptr, const struct hmac *hmac); +void fromwire_hmac(const u8 **ptr, size_t *max, struct hmac *hmac); + +/* Define hmac_eq. */ +STRUCTEQ_DEF(hmac, 0, bytes); + +#endif /* LIGHTNING_COMMON_HMAC_H */