From: rasky Date: Fri, 24 Sep 2010 16:23:12 +0000 (+0000) Subject: SEC: add generic interface for key-derivation functions. X-Git-Tag: 2.6.0~97 X-Git-Url: https://codewiz.org/gitweb?a=commitdiff_plain;h=4ec9559a050632e54a74bb9179c2efe56e926070;p=bertos.git SEC: add generic interface for key-derivation functions. git-svn-id: https://src.develer.com/svnoss/bertos/trunk@4304 38d2e660-2303-0410-9eaa-f027e97ec537 --- diff --git a/bertos/sec/kdf.h b/bertos/sec/kdf.h new file mode 100644 index 00000000..48ae1c74 --- /dev/null +++ b/bertos/sec/kdf.h @@ -0,0 +1,95 @@ +/** + * \file + * + * + * \brief Generic interface for key derivation functions. + * \author Giovanni Bajo + * + */ + +#ifndef SEC_KDF_H +#define SEC_KDF_H + +#include +#include +#include +#include + +typedef struct Kdf +{ + const uint8_t* block; + size_t block_len; + size_t to_read; + + void (*begin)(struct Kdf *kdf, const char *pwd, size_t pwd_len, + const uint8_t *salt, size_t salt_len); + void (*next)(struct Kdf *kdf); +} Kdf; + +/** + * Initialize the key derivation function, with the specified \a password and \a salt. + */ +INLINE void kdf_begin(Kdf *kdf, const char *pwd, size_t pwd_len, + const uint8_t *salt, size_t salt_len) +{ + ASSERT(kdf->begin); + kdf->begin(kdf, pwd, pwd_len, salt, salt_len); +} + +/** + * Extract \a len derived bytes into the \a out buffer. + * + * After having initialized the derivation function iwth \a kdf_begin, you can call + * this function multiple times, to produce several batches of derived data. + * + * \note Some algorithms implementing this API might have a maximum length of bytes + * that can be derived, after which they will simply ASSERT(). + */ +INLINE void kdf_read(Kdf *kdf, uint8_t *out, size_t len) +{ + do + { + if (kdf->to_read == 0) + { + kdf->next(kdf); + ASSERT(kdf->to_read != 0); + } + + size_t c = MIN(len, kdf->to_read); + memcpy(out, kdf->block, c); + len -= c; + out += c; + kdf->block += c; + kdf->to_read -= c; + } while (len); +} + +#endif /* SEC_KDF_H */