X-Git-Url: https://codewiz.org/gitweb?a=blobdiff_plain;f=bertos%2Fsec%2Fkdf%2Fpbkdf2.c;fp=bertos%2Fsec%2Fkdf%2Fpbkdf2.c;h=e3d1f5f823aa7596d2120eefd74324845066d124;hb=5b8a5d2a4459f7f1a500e56a12fd39acb2bb04fc;hp=0000000000000000000000000000000000000000;hpb=4ec9559a050632e54a74bb9179c2efe56e926070;p=bertos.git diff --git a/bertos/sec/kdf/pbkdf2.c b/bertos/sec/kdf/pbkdf2.c new file mode 100644 index 00000000..e3d1f5f8 --- /dev/null +++ b/bertos/sec/kdf/pbkdf2.c @@ -0,0 +1,113 @@ +/** + * \file + * + * + * \brief PBKDF2 implementation + * \author Giovanni Bajo + * + */ + +#include "pbkdf2.h" +#include +#include +#include + +static void PBKDF2_begin(Kdf *ctx_, const char *pwd, size_t pwd_len, + const uint8_t *salt, size_t salt_len) +{ + PBKDF2_Context *ctx = (PBKDF2_Context*)ctx_; + + ASSERT(sizeof(ctx->salt) >= salt_len); + + mac_set_key(ctx->mac, (const uint8_t*)pwd, pwd_len); + ctx->salt_len = salt_len; + memcpy(ctx->salt, salt, salt_len); + ctx->c = 0; + ctx->kdf.to_read = 0; + ctx->kdf.block = NULL; +} + +static void PBKDF2_next(Kdf *ctx_) +{ + PBKDF2_Context *ctx = (PBKDF2_Context*)ctx_; + int dlen = mac_digest_len(ctx->mac); + uint8_t last[dlen]; + + ++ctx->c; + uint32_t bec = cpu_to_be32(ctx->c); + + mac_begin(ctx->mac); + mac_update(ctx->mac, ctx->salt, ctx->salt_len); + mac_update(ctx->mac, &bec, 4); + memcpy(last, mac_final(ctx->mac), dlen); + memcpy(ctx->block, last, dlen); + + for (uint32_t i=0; iiterations-1; ++i) + { + mac_begin(ctx->mac); + mac_update(ctx->mac, last, dlen); + memcpy(last, mac_final(ctx->mac), dlen); + xor_block(ctx->block, ctx->block, last, dlen); + } + + ctx->kdf.to_read = dlen; + ctx->kdf.block = ctx->block; + + PURGE(last); +} + + +/**********************************************************************/ + +// Default iteration count. The RFC does not specify a "good" default +// value; it just says that this should be a high value to slow down +// computations. Since slowing down is not much of a concern for an +// embedded system, we settle for a value which is not too big. +#define PBKDF2_DEFAULT_ITERATIONS 100 + + +void PBKDF2_init(PBKDF2_Context *ctx, Mac *mac) +{ + ctx->salt_len = 0; + ctx->mac = mac; + ctx->iterations = PBKDF2_DEFAULT_ITERATIONS; + ctx->kdf.begin = PBKDF2_begin; + ctx->kdf.next = PBKDF2_next; + ctx->kdf.block_len = mac_digest_len(mac); + ASSERT(ctx->kdf.block_len <= sizeof(ctx->block)); +} + +void PBKDF2_set_iterations(Kdf *ctx_, uint32_t iterations) +{ + PBKDF2_Context *ctx = (PBKDF2_Context*)ctx_; + ctx->iterations = iterations; +} +