This is an automated email from the ASF dual-hosted git repository.

ronny pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/couchdb-fast-pbkdf2.git

commit f9ee306fa2da3f5c2f0089a11ce53ccafb1546e8
Author: Nelson Vides <nelson.vi...@erlang-solutions.com>
AuthorDate: Wed Feb 10 20:13:20 2021 +0100

    Port pbkdf2 specifics from fast_scram
---
 .github/workflows/ci.yml |  28 +++
 .gitignore               |  30 +++
 LICENSE                  | 191 +++++++++++++++
 Makefile                 |  31 +++
 README.md                |  57 +++++
 benchmarks/bench.ex      |  36 +++
 c_src/fast_pbkdf2.c      | 592 +++++++++++++++++++++++++++++++++++++++++++++++
 mix.exs                  |  18 ++
 mix.lock                 |   4 +
 rebar.config             |  48 ++++
 rebar.lock               |   1 +
 src/fast_pbkdf2.app.src  |  15 ++
 src/fast_pbkdf2.erl      |  51 ++++
 test/erl_pbkdf2.erl      |  36 +++
 test/pbkdf2_SUITE.erl    | 204 ++++++++++++++++
 15 files changed, 1342 insertions(+)

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..545d6a9
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,28 @@
+name: ci
+
+on:
+  push:
+    branches: [ master ]
+  pull_request:
+    branches: [ master ]
+  workflow_dispatch:
+
+jobs:
+  test:
+    name: OTP ${{matrix.otp}}
+    strategy:
+      matrix:
+        otp: ['23.2', '22.3', '21.3']
+    runs-on: 'ubuntu-20.04'
+    steps:
+      - uses: actions/checkout@v2
+      - uses: ErlGang/setup-erlang@v1.0.0
+        with:
+          otp-version: ${{ matrix.otp }}
+      - run: make rebar3
+      - run: make
+      - run: make test
+      - run: make dialyzer
+      - run: make codecov
+      - run: pip install --user codecov
+      - run: /home/runner/.local/bin/codecov
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0154361
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,30 @@
+.rebar3
+_*
+.eunit
+*.o
+*.d
+*.beam
+*.plt
+*.swp
+*.swo
+.erlang.cookie
+ebin
+log
+erl_crash.dump
+.rebar
+logs
+_build
+.idea
+*.iml
+rebar3.crashdump
+*~
+*.vim
+tags
+priv/
+/deps/
+/doc/
+/.fetch
+erl_crash.dump
+*.ez
+*.tar
+
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..a2958c7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,191 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   Copyright 2020, Nelson Vides <nelson.vi...@erlang-solutions.com>.
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..18c74d0
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,31 @@
+.PHONY: rel deps test
+
+all: deps compile
+
+compile: rebar3
+       ./rebar3 compile
+
+deps: rebar3
+       ./rebar3 get-deps
+
+clean: rebar3
+       ./rebar3 clean
+
+test-deps: rebar3
+       ./rebar3 get-deps
+
+test-compile: rebar3 test-deps
+       ./rebar3 compile
+
+test: test-compile
+       ./rebar3 as test ct
+
+codecov: _build/test/cover/ct.coverdata
+       ./rebar3 as test codecov analyze
+
+rebar3:
+       wget https://github.com/erlang/rebar3/releases/download/3.13.2/rebar3 
&&\
+       chmod u+x rebar3
+
+dialyzer: rebar3
+       ./rebar3 dialyzer
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d9e90b0
--- /dev/null
+++ b/README.md
@@ -0,0 +1,57 @@
+# Fast PBKDF2
+
+[![Actions 
Status](https://github.com/esl/fast_pbkdf2/workflows/ci/badge.svg)](https://github.com/esl/fast_pbkdf2/actions)
+[![codecov](https://codecov.io/gh/esl/fast_pbkdf2/branch/main/graph/badge.svg)](https://codecov.io/gh/esl/fast_pbkdf2)
+[![Hex](http://img.shields.io/hexpm/v/fast_pbkdf2.svg)](https://hex.pm/packages/fast_pbkdf2)
+
+`fast_pbkdf2` is an Erlang implementation of the [PBKDF2][PBKDF2], where the 
algorithm is a carefully-optimised NIF that uses timeslicing and nif scheduling 
to respect the latency properties of the BEAM.
+
+## Building
+`fast_pbkdf2` is a rebar3-compatible OTP application, that uses the 
[port_compiler](https://github.com/blt/port_compiler) for the C part of the 
code.
+
+Building is as easy as `rebar3 compile`, and using it in your projects as
+```erlang
+{deps,
+ [{fast_pbkdf2, "1.0.0"}]}.
+{plugins, [pc, rebar3_hex]}.
+{provider_hooks,
+ [{pre,
+   [{compile, {pc, compile}},
+    {clean, {pc, clean}}]}]}.
+```
+
+## Using
+
+```erlang
+DerivedPassword = fast_pbkdf2:pbkdf2(Hash, Password, Salt, IterationCount)
+```
+where `Hash` is the underlying hash function chosen as described by
+```erlang
+-type sha_type() :: crypto:sha1() | crypto:sha2().
+```
+
+### Custom `dkLen`
+If what you desire is PBKDF2 with custom `dkLen`(I assume that if that is what 
you want, then you know your RFC), in a way that allows you to request longer 
derived keys, you may use `fast_pbkdf2:pbkdf2_block/5` with a given block index 
and do the indexing and chunking yourself, or use `fast_pbkdf2:pbkdf2/5` for 
the full algorithm. However, it doesn't really add much more entropy to the 
derived key to use outputs larger than the output of the underlying hash, so 
you might as well, use `p [...]
+
+## Performance
+
+### The problem
+PBKDF2 is a challenge derivation method, that is, it forces the client to 
compute a challenge in order to derive the desired password. But when the 
server implementation is slower than that of an attacker, it makes the server 
vulnerable to DoS by hogging itself with computations. We could see that on the 
CI and load-testing pipelines of [MongooseIM][MIM] for example.
+
+### The solution
+Is partial. We don't expect to have the fastest implementation, as that would 
be purely C code on GPUs, so unfortunately an attacker will pretty much always 
have better chances there. _But_ we can make the computation cheap enough for 
us that other computations —like the load of a session establishment— will be 
more relevant than that of the challenge; and also that other defence 
mechanisms like IP blacklisting or traffic shaping, will fire in good time.
+
+### The outcome
+On average it's 10x faster on the machines I've tested it (you can compare 
using the provided module in `./benchmarks/bench.ex`), but while the erlang 
implementation consumes memory linearly to the iteration count (1M it count 
with 120 clients quickly allocated 7GB of RAM, and 1M is common for password 
managers for example), the NIF implementation does not allocate any more 
memory. Also, the NIFS spend all of their time in user level alone, while the 
erlang one jumps to system calls in a [...]
+
+## Credit where credit is due
+The initial algorithm and optimisations were taken from Joseph Birr-Pixton's
+[fastpbkdf2](https://github.com/ctz/fastpbkdf2)'s repository.
+
+## Read more:
+* Password-Based Cryptography Specification (PBKDF2): 
[RFC8018](https://tools.ietf.org/html/rfc8018#section-5.2)
+* HMAC: [RFC2104]( https://tools.ietf.org/html/rfc2104)
+* SHAs and HMAC-SHA: [RFC6234](https://tools.ietf.org/html/rfc6234)
+
+[MIM]: https://github.com/esl/MongooseIM
+[PBKDF2]: https://tools.ietf.org/html/rfc8018#section-5.2
diff --git a/benchmarks/bench.ex b/benchmarks/bench.ex
new file mode 100644
index 0000000..79464c8
--- /dev/null
+++ b/benchmarks/bench.ex
@@ -0,0 +1,36 @@
+defmodule PBKDF2.Benchmarks do
+  def pbkdf2_input itCount do
+    password = :base64.encode(:crypto.strong_rand_bytes(10))
+    salt = :base64.encode(:crypto.strong_rand_bytes(16))
+    {password, salt, itCount}
+  end
+
+  def pbkdf2 {password, salt, it_count} do
+    :fast_pbkdf2.pbkdf2(:sha256, password, salt, it_count)
+  end
+end
+
+{:ok, :erl_pbkdf2} = :compile.file('./test/erl_pbkdf2.erl')
+
+Benchee.run(
+  %{
+    "fast_pbkdf2" => fn {password, salt, it_count} ->
+        :fast_pbkdf2.pbkdf2(:sha256, password, salt, it_count)
+      end,
+    "erl_pbkdf2 " => fn {password, salt, it_count} ->
+        :erl_pbkdf2.pbkdf2_oneblock(:sha256, password, salt, it_count)
+      end
+  },
+  inputs: %{
+    "1. 8" => PBKDF2.Benchmarks.pbkdf2_input(8),
+    "2. 512" => PBKDF2.Benchmarks.pbkdf2_input(512),
+    "3. 4096" => PBKDF2.Benchmarks.pbkdf2_input(4096),
+    "4. 10000" => PBKDF2.Benchmarks.pbkdf2_input(10000),
+    "5. 160000" => PBKDF2.Benchmarks.pbkdf2_input(160000),
+    "6. 500000" => PBKDF2.Benchmarks.pbkdf2_input(500000)
+  },
+  parallel: 12,
+  time: 5,
+  memory_time: 5
+)
+
diff --git a/c_src/fast_pbkdf2.c b/c_src/fast_pbkdf2.c
new file mode 100644
index 0000000..680950e
--- /dev/null
+++ b/c_src/fast_pbkdf2.c
@@ -0,0 +1,592 @@
+/*
+ * fast-pbkdf2 - Optimal PBKDF2-HMAC calculation
+ * Written in 2015 by Joseph Birr-Pixton <jpix...@gmail.com>
+ *
+ * To the extent possible under law, the author(s) have dedicated all
+ * copyright and related and neighboring rights to this software to the
+ * public domain worldwide. This software is distributed without any
+ * warranty.
+ *
+ * You should have received a copy of the CC0 Public Domain Dedication
+ * along with this software. If not, see
+ * <http://creativecommons.org/publicdomain/zero/1.0/>.
+ */
+
+#include "erl_nif.h"
+
+#ifndef TIMESLICE_PERCENTAGE
+#define TIMESLICE_PERCENTAGE 5 // announce a timeslice of 5 percent when 
indicated
+#define ITERS_PER_SLOT 6
+/* On the single core of an 2,2 GHz Quad-Core Intel Core i7, in slightly below 
1ms
+ * we achieve around 120 iterations for sha512.
+ * Also, we want to report percentage every 5% (TIMESLICE_PERCENTAGE).
+ * We therefore get that a slot in between iterations should take 6 iterations 
(ITERS_PER_SLOT).
+ */
+#endif
+
+#include <assert.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdint.h>
+#if defined(__GNUC__)
+#include <sys/types.h>
+#endif
+
+#include <openssl/sha.h>
+
+/* --- Common useful things --- */
+
+static inline void write32_be(uint32_t n, uint8_t out[4])
+{
+#if defined(__GNUC__) && __GNUC__ >= 4 && __BYTE_ORDER == __LITTLE_ENDIAN
+  *(uint32_t *)(out) = __builtin_bswap32(n);
+#else
+  out[0] = (n >> 24) & 0xff;
+  out[1] = (n >> 16) & 0xff;
+  out[2] = (n >> 8) & 0xff;
+  out[3] = n & 0xff;
+#endif
+}
+
+static inline void write64_be(uint64_t n, uint8_t out[8])
+{
+#if defined(__GNUC__) &&  __GNUC__ >= 4 && __BYTE_ORDER == __LITTLE_ENDIAN
+  *(uint64_t *)(out) = __builtin_bswap64(n);
+#else
+  write32_be((n >> 32) & 0xffffffff, out);
+  write32_be(n & 0xffffffff, out + 4);
+#endif
+}
+
+/* Prepare block (of blocksz bytes) to contain md padding denoting a msg-size
+ * message (in bytes).  block has a prefix of used bytes.
+ * Message length is expressed in 32 bits (so suitable for all sha1 and sha2 
algorithms). */
+static inline void md_pad(uint8_t *block, size_t blocksz, size_t used, size_t 
msg)
+{
+  memset(block + used, 0, blocksz - used - 4);
+  block[used] = 0x80;
+  block += blocksz - 4;
+  write32_be((uint32_t) (msg * 8), block);
+}
+
+/* Internal function/type names for hash-specific things. */
+#define XSTRINGIFY(s) STRINGIFY(s)
+#define STRINGIFY(s) #s
+
+#define HMAC_CTX(_name) HMAC_ ## _name ## _ctx
+#define HMAC_INIT(_name) HMAC_ ## _name ## _init
+#define HMAC_UPDATE(_name) HMAC_ ## _name ## _update
+#define HMAC_FINAL(_name) HMAC_ ## _name ## _final
+
+#define HMAC_CTX_ROUND(_name) HMAC_ ## _name ## _ctx_round           // C 
struct
+#define HMAC_CTX_ROUND_RES(_name) res_HMAC_ ## _name ## _ctx_round   // Erlang 
Resource definition
+#define HMAC_CTX_ROUND_NAME(_name) XSTRINGIFY(HMAC_CTX_ROUND(_name)) // Erlang 
atom-name
+
+#define PBKDF2_F(_name) pbkdf2_f_ ## _name
+#define PBKDF2(_name) pbkdf2_ ## _name
+
+typedef struct {
+    ERL_NIF_TERM atom_sha;
+    ERL_NIF_TERM atom_sha224;
+    ERL_NIF_TERM atom_sha256;
+    ERL_NIF_TERM atom_sha384;
+    ERL_NIF_TERM atom_sha512;
+    ErlNifResourceType* HMAC_CTX_ROUND_RES(sha1);
+    ErlNifResourceType* HMAC_CTX_ROUND_RES(sha224);
+    ErlNifResourceType* HMAC_CTX_ROUND_RES(sha256);
+    ErlNifResourceType* HMAC_CTX_ROUND_RES(sha384);
+    ErlNifResourceType* HMAC_CTX_ROUND_RES(sha512);
+} pbkdf2_st;
+
+/* This macro expands to decls for the whole implementation for a given
+ * hash function.  Arguments are:
+ *
+ * _name like 'sha1', added to symbol names                         (e.g. 
sha256)
+ * _blocksz block size, in bytes                                    (e.g. 
SHA256_CBLOCK)
+ * _hashsz digest output, in bytes                                  (e.g. 
SHA256_DIGEST_LENGTH)
+ * _ctx hash context type                                           (e.g. 
SHA256_Init)
+ * _init hash context initialisation function                       (e.g. 
SHA256_Update)
+ *    args: (_ctx *c)
+ * _update hash context update function                             (e.g. 
SHA256_Update)
+ *    args: (_ctx *c, const void *data, size_t ndata)
+ * _final hash context finish function                              (e.g. 
SHA256_Final)
+ *    args: (void *out, _ctx *c)
+ * _xform hash context raw block update function                    (e.g. 
SHA256_Transform)
+ *    args: (_ctx *c, const void *data)
+ * _xcpy hash context raw copy function (only need copy hash state) (e.g. 
sha256_cpy)
+ *    args: (_ctx * restrict out, const _ctx *restrict in)
+ * _xtract hash context state extraction                            (e.g. 
sha256_extract)
+ *    args: args (_ctx *restrict c, uint8_t *restrict out)
+ * _xxor hash context xor function (only need xor hash state)       (e.g. 
sha256_xor)
+ *    args: (_ctx *restrict out, const _ctx *restrict in)
+ *
+ * The resulting function is named PBKDF2(_name).
+ */
+#define DECL_PBKDF2(_name, _blocksz, _hashsz, _ctx,                           \
+                    _init, _update, _xform, _final, _xcpy, _xtract, _xxor)    \
+                                                                              \
+  typedef struct {                                                            \
+    _ctx inner;                                                               \
+    _ctx outer;                                                               \
+  } HMAC_CTX(_name);                                                          \
+                                                                              \
+  typedef struct {                                                            \
+      HMAC_CTX(_name) startctx;                                               \
+      HMAC_CTX(_name) ctx;                                                    \
+      _ctx            result;                                                 \
+      uint8_t         Ublock[_blocksz];                                       \
+      uint32_t        iterations;                                             \
+  } HMAC_CTX_ROUND(_name);                                                    \
+                                                                              \
+  static inline void HMAC_INIT(_name)(HMAC_CTX(_name) *ctx,                   \
+                                      const uint8_t *key, size_t nkey)        \
+  {                                                                           \
+    /* Prepare key: */                                                        \
+    uint8_t k[_blocksz];                                                      \
+                                                                              \
+    /* Shorten long keys. */                                                  \
+    if (nkey > _blocksz)                                                      \
+    {                                                                         \
+      _init(&ctx->inner);                                                     \
+      _update(&ctx->inner, key, nkey);                                        \
+      _final(k, &ctx->inner);                                                 \
+      key = k;                                                                \
+      nkey = _hashsz;                                                         \
+    }                                                                         \
+                                                                              \
+    /* Standard doesn't cover case where blocksz < hashsz. */                 \
+    assert(nkey <= _blocksz);                                                 \
+                                                                              \
+    /* Right zero-pad short keys. */                                          \
+    if (k != key)                                                             \
+      memcpy(k, key, nkey);                                                   \
+    if (_blocksz > nkey)                                                      \
+      memset(k + nkey, 0, _blocksz - nkey);                                   \
+                                                                              \
+    /* Start inner hash computation */                                        \
+    uint8_t blk_inner[_blocksz];                                              \
+    uint8_t blk_outer[_blocksz];                                              \
+                                                                              \
+    for (size_t i = 0; i < _blocksz; i++)                                     \
+    {                                                                         \
+      blk_inner[i] = 0x36 ^ k[i];                                             \
+      blk_outer[i] = 0x5c ^ k[i];                                             \
+    }                                                                         \
+                                                                              \
+    _init(&ctx->inner);                                                       \
+    _update(&ctx->inner, blk_inner, sizeof blk_inner);                        \
+                                                                              \
+    /* And outer. */                                                          \
+    _init(&ctx->outer);                                                       \
+    _update(&ctx->outer, blk_outer, sizeof blk_outer);                        \
+  }                                                                           \
+                                                                              \
+  static inline void HMAC_UPDATE(_name)(HMAC_CTX(_name) *ctx,                 \
+                                        const void *data, size_t ndata)       \
+  {                                                                           \
+    _update(&ctx->inner, data, ndata);                                        \
+  }                                                                           \
+                                                                              \
+  static inline void HMAC_FINAL(_name)(HMAC_CTX(_name) *ctx,                  \
+                                       uint8_t out[_hashsz])                  \
+  {                                                                           \
+    _final(out, &ctx->inner);                                                 \
+    _update(&ctx->outer, out, _hashsz);                                       \
+    _final(out, &ctx->outer);                                                 \
+  }                                                                           \
+                                                                              \
+  /* --- PBKDF2 --- */                                                        \
+  ERL_NIF_TERM PBKDF2_F(_name)(ErlNifEnv *env,                                \
+                               int argc, const ERL_NIF_TERM argv[])           \
+  {                                                                           \
+    pbkdf2_st *mod_st = enif_priv_data(env);                                  \
+    HMAC_CTX_ROUND(_name) *round_st;                                          \
+    enif_get_resource(env, argv[0],                                           \
+            mod_st->HMAC_CTX_ROUND_RES(_name),                                \
+            ((void*) (&round_st)));                                           \
+                                                                              \
+    while (1) {                                                               \
+        for (uint32_t i = 0; i < ITERS_PER_SLOT && i < round_st->iterations-1; 
++i) \
+        {                                                                     \
+            /* Complete inner hash with previous U */                         \
+            _xcpy(&round_st->ctx.inner, &round_st->startctx.inner);           \
+            _xform(&round_st->ctx.inner, round_st->Ublock);                   \
+            _xtract(&round_st->ctx.inner, round_st->Ublock);                  \
+            /* Complete outer hash with inner output */                       \
+            _xcpy(&round_st->ctx.outer, &round_st->startctx.outer);           \
+            _xform(&round_st->ctx.outer, round_st->Ublock);                   \
+            _xtract(&round_st->ctx.outer, round_st->Ublock);                  \
+            _xxor(&round_st->result, &round_st->ctx.outer);                   \
+        }                                                                     \
+        if (round_st->iterations <= ITERS_PER_SLOT) break;                    \
+        round_st->iterations -= ITERS_PER_SLOT;                               \
+                                                                              \
+        /* Schedule again but with iterations decremented */                  \
+        if (enif_consume_timeslice(env, TIMESLICE_PERCENTAGE)) {              \
+            return enif_schedule_nif(env, HMAC_CTX_ROUND_NAME(_name), 0,      \
+                    PBKDF2_F(_name), argc, argv);                             \
+        }                                                                     \
+    }                                                                         \
+                                                                              \
+    /* We're done, so we can release the resource */                          \
+    enif_release_resource(round_st);                                          \
+    /* Reform result into output buffer. */                                   \
+    ERL_NIF_TERM erl_result;                                                  \
+    unsigned char *output = enif_make_new_binary(env, _hashsz, &erl_result);  \
+    _xtract(&round_st->result, output);                                       \
+    return erl_result;                                                        \
+  }                                                                           \
+                                                                              \
+  static inline ERL_NIF_TERM PBKDF2(_name)(ErlNifEnv *env,                    \
+                     const uint8_t *pw, size_t npw,                           \
+                     const uint8_t *salt, size_t nsalt,                       \
+                     uint32_t iterations, uint32_t counter)                   \
+  {                                                                           \
+    /* Retrieve the state resource descriptor from our priv data, */          \
+    /* and allocate a new resource structure */                               \
+    pbkdf2_st *mod_st = enif_priv_data(env);                                  \
+    HMAC_CTX_ROUND(_name) *round_st = enif_alloc_resource(                    \
+        mod_st->HMAC_CTX_ROUND_RES(_name),                                    \
+        sizeof(HMAC_CTX_ROUND(_name))                                         \
+    );                                                                        \
+                                                                              \
+    HMAC_INIT(_name)(&round_st->startctx, pw, npw);                           \
+    uint8_t countbuf[4];                                                      \
+    write32_be(counter, countbuf);                                            \
+                                                                              \
+    /* Prepare loop-invariant padding block. */                               \
+    md_pad(round_st->Ublock, _blocksz, _hashsz, _blocksz + _hashsz);          \
+                                                                              \
+    /* First iteration:                                                       \
+     *   U_1 = PRF(P, S || INT_32_BE(i))                                      \
+     */                                                                       \
+    round_st->ctx = round_st->startctx;                                       \
+    HMAC_UPDATE(_name)(&round_st->ctx, salt, nsalt);                          \
+    HMAC_UPDATE(_name)(&round_st->ctx, countbuf, sizeof countbuf);            \
+    HMAC_FINAL(_name)(&round_st->ctx, round_st->Ublock);                      \
+    round_st->result = round_st->ctx.outer;                                   \
+    round_st->iterations = iterations;                                        \
+                                                                              \
+    ERL_NIF_TERM state_term = enif_make_resource(env, round_st);              \
+    const ERL_NIF_TERM tmp_argv[] = {state_term};                             \
+    return PBKDF2_F(_name)(env, 1, tmp_argv);                                 \
+  }
+
+
+static inline void sha1_extract(SHA_CTX *restrict ctx, uint8_t *restrict out)
+{
+  write32_be(ctx->h0, out);
+  write32_be(ctx->h1, out + 4);
+  write32_be(ctx->h2, out + 8);
+  write32_be(ctx->h3, out + 12);
+  write32_be(ctx->h4, out + 16);
+}
+
+static inline void sha1_cpy(SHA_CTX *restrict out, const SHA_CTX *restrict in)
+{
+  out->h0 = in->h0;
+  out->h1 = in->h1;
+  out->h2 = in->h2;
+  out->h3 = in->h3;
+  out->h4 = in->h4;
+}
+
+static inline void sha1_xor(SHA_CTX *restrict out, const SHA_CTX *restrict in)
+{
+  out->h0 ^= in->h0;
+  out->h1 ^= in->h1;
+  out->h2 ^= in->h2;
+  out->h3 ^= in->h3;
+  out->h4 ^= in->h4;
+}
+
+DECL_PBKDF2(sha1,
+            SHA_CBLOCK,
+            SHA_DIGEST_LENGTH,
+            SHA_CTX,
+            SHA1_Init,
+            SHA1_Update,
+            SHA1_Transform,
+            SHA1_Final,
+            sha1_cpy,
+            sha1_extract,
+            sha1_xor)
+
+static inline void sha224_extract(SHA256_CTX *restrict ctx, uint8_t *restrict 
out)
+{
+  write32_be(ctx->h[0], out);
+  write32_be(ctx->h[1], out + 4);
+  write32_be(ctx->h[2], out + 8);
+  write32_be(ctx->h[3], out + 12);
+  write32_be(ctx->h[4], out + 16);
+  write32_be(ctx->h[5], out + 20);
+  write32_be(ctx->h[6], out + 24);
+}
+
+static inline void sha256_extract(SHA256_CTX *restrict ctx, uint8_t *restrict 
out)
+{
+  write32_be(ctx->h[0], out);
+  write32_be(ctx->h[1], out + 4);
+  write32_be(ctx->h[2], out + 8);
+  write32_be(ctx->h[3], out + 12);
+  write32_be(ctx->h[4], out + 16);
+  write32_be(ctx->h[5], out + 20);
+  write32_be(ctx->h[6], out + 24);
+  write32_be(ctx->h[7], out + 28);
+}
+
+static inline void sha256_cpy(SHA256_CTX *restrict out, const SHA256_CTX 
*restrict in)
+{
+  out->h[0] = in->h[0];
+  out->h[1] = in->h[1];
+  out->h[2] = in->h[2];
+  out->h[3] = in->h[3];
+  out->h[4] = in->h[4];
+  out->h[5] = in->h[5];
+  out->h[6] = in->h[6];
+  out->h[7] = in->h[7];
+}
+
+static inline void sha256_xor(SHA256_CTX *restrict out, const SHA256_CTX 
*restrict in)
+{
+  out->h[0] ^= in->h[0];
+  out->h[1] ^= in->h[1];
+  out->h[2] ^= in->h[2];
+  out->h[3] ^= in->h[3];
+  out->h[4] ^= in->h[4];
+  out->h[5] ^= in->h[5];
+  out->h[6] ^= in->h[6];
+  out->h[7] ^= in->h[7];
+}
+
+DECL_PBKDF2(sha224,
+            SHA256_CBLOCK,
+            SHA224_DIGEST_LENGTH,
+            SHA256_CTX,
+            SHA224_Init,
+            SHA224_Update,
+            SHA256_Transform,
+            SHA224_Final,
+            sha256_cpy,
+            sha224_extract,
+            sha256_xor)
+
+DECL_PBKDF2(sha256,
+            SHA256_CBLOCK,
+            SHA256_DIGEST_LENGTH,
+            SHA256_CTX,
+            SHA256_Init,
+            SHA256_Update,
+            SHA256_Transform,
+            SHA256_Final,
+            sha256_cpy,
+            sha256_extract,
+            sha256_xor)
+
+static inline void sha384_extract(SHA512_CTX *restrict ctx, uint8_t *restrict 
out)
+{
+  write64_be(ctx->h[0], out);
+  write64_be(ctx->h[1], out + 8);
+  write64_be(ctx->h[2], out + 16);
+  write64_be(ctx->h[3], out + 24);
+  write64_be(ctx->h[4], out + 32);
+  write64_be(ctx->h[5], out + 40);
+}
+
+static inline void sha512_extract(SHA512_CTX *restrict ctx, uint8_t *restrict 
out)
+{
+  write64_be(ctx->h[0], out);
+  write64_be(ctx->h[1], out + 8);
+  write64_be(ctx->h[2], out + 16);
+  write64_be(ctx->h[3], out + 24);
+  write64_be(ctx->h[4], out + 32);
+  write64_be(ctx->h[5], out + 40);
+  write64_be(ctx->h[6], out + 48);
+  write64_be(ctx->h[7], out + 56);
+}
+
+static inline void sha512_cpy(SHA512_CTX *restrict out, const SHA512_CTX 
*restrict in)
+{
+  out->h[0] = in->h[0];
+  out->h[1] = in->h[1];
+  out->h[2] = in->h[2];
+  out->h[3] = in->h[3];
+  out->h[4] = in->h[4];
+  out->h[5] = in->h[5];
+  out->h[6] = in->h[6];
+  out->h[7] = in->h[7];
+}
+
+static inline void sha512_xor(SHA512_CTX *restrict out, const SHA512_CTX 
*restrict in)
+{
+  out->h[0] ^= in->h[0];
+  out->h[1] ^= in->h[1];
+  out->h[2] ^= in->h[2];
+  out->h[3] ^= in->h[3];
+  out->h[4] ^= in->h[4];
+  out->h[5] ^= in->h[5];
+  out->h[6] ^= in->h[6];
+  out->h[7] ^= in->h[7];
+}
+
+DECL_PBKDF2(sha384,
+            SHA512_CBLOCK,
+            SHA384_DIGEST_LENGTH,
+            SHA512_CTX,
+            SHA384_Init,
+            SHA384_Update,
+            SHA512_Transform,
+            SHA384_Final,
+            sha512_cpy,
+            sha384_extract,
+            sha512_xor)
+
+DECL_PBKDF2(sha512,
+            SHA512_CBLOCK,
+            SHA512_DIGEST_LENGTH,
+            SHA512_CTX,
+            SHA512_Init,
+            SHA512_Update,
+            SHA512_Transform,
+            SHA512_Final,
+            sha512_cpy,
+            sha512_extract,
+            sha512_xor)
+
+static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)
+{
+    (void) load_info;
+    pbkdf2_st* mod_st = enif_alloc(sizeof(pbkdf2_st));
+    if(mod_st == NULL) {
+        return 1;
+    }
+
+    mod_st->atom_sha = enif_make_atom(env, "sha");
+    mod_st->atom_sha224 = enif_make_atom(env, "sha224");
+    mod_st->atom_sha256 = enif_make_atom(env, "sha256");
+    mod_st->atom_sha384 = enif_make_atom(env, "sha384");
+    mod_st->atom_sha512 = enif_make_atom(env, "sha512");
+
+    mod_st->HMAC_CTX_ROUND_RES(sha1) = enif_open_resource_type(
+            env, NULL, HMAC_CTX_ROUND_NAME(sha1),
+            NULL, ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER, NULL
+        );
+
+    mod_st->HMAC_CTX_ROUND_RES(sha224) = enif_open_resource_type(
+            env, NULL, HMAC_CTX_ROUND_NAME(sha224),
+            NULL, ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER, NULL
+        );
+
+    mod_st->HMAC_CTX_ROUND_RES(sha256) = enif_open_resource_type(
+            env, NULL, HMAC_CTX_ROUND_NAME(sha256),
+            NULL, ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER, NULL
+        );
+
+    mod_st->HMAC_CTX_ROUND_RES(sha384) = enif_open_resource_type(
+            env, NULL, HMAC_CTX_ROUND_NAME(sha384),
+            NULL, ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER, NULL
+        );
+
+    mod_st->HMAC_CTX_ROUND_RES(sha512) = enif_open_resource_type(
+            env, NULL, HMAC_CTX_ROUND_NAME(sha512),
+            NULL, ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER, NULL
+        );
+
+    *priv_data = (void*) mod_st;
+
+    return 0;
+}
+
+static int reload(ErlNifEnv* env, void** priv, ERL_NIF_TERM info)
+{
+    return 0;
+}
+
+static int upgrade(ErlNifEnv* env, void** priv, void** old_priv, ERL_NIF_TERM 
info)
+{
+    return load(env, priv, info);
+}
+
+static void unload(ErlNifEnv* env, void* priv)
+{
+    enif_free(priv);
+    return;
+}
+
+ERL_NIF_TERM mk_error(ErlNifEnv* env, const char *error_msg)
+{
+    return enif_make_tuple2(
+            env,
+            enif_make_atom(env, "error"),
+            enif_make_atom(env, error_msg)
+            );
+}
+
+static ERL_NIF_TERM
+pbkdf2_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
+{
+    if(argc != 5)
+        return enif_make_badarg(env);
+
+    ErlNifBinary password;
+    if (!enif_inspect_binary(env, argv[1], &password))
+        return mk_error(env, "bad_password");
+
+    ErlNifBinary salt;
+    if (!enif_inspect_binary(env, argv[2], &salt))
+        return mk_error(env, "bad_salt");
+
+    int iteration_count;
+    if (!enif_get_int(env, argv[3], &iteration_count))
+        return mk_error(env, "bad_iteration_count");
+    if (iteration_count <= 0)
+        return mk_error(env, "bad_iteration_count");
+
+    int counter;
+    if (!enif_get_int(env, argv[4], &counter))
+        return mk_error(env, "bad_block_counter");
+    if (counter <= 0)
+        return mk_error(env, "bad_block_counter");
+
+    /** Calculates PBKDF2-HMAC-SHA
+     *  @p npw bytes at @p pw are the password input.
+     *  @p nsalt bytes at @p salt are the salt input.
+     *  @p iterations is the PBKDF2 iteration count and must be non-zero.
+     */
+    pbkdf2_st *mod_st = (pbkdf2_st*) enif_priv_data(env);
+
+    if(enif_is_identical(argv[0], mod_st->atom_sha)) {
+        return PBKDF2(sha1)(env,
+                password.data, password.size,
+                salt.data, salt.size,
+                iteration_count, counter);
+    } else if(enif_is_identical(argv[0], mod_st->atom_sha224)) {
+        return PBKDF2(sha224)(env,
+                password.data, password.size,
+                salt.data, salt.size,
+                iteration_count, counter);
+    } else if(enif_is_identical(argv[0], mod_st->atom_sha256)) {
+        return PBKDF2(sha256)(env,
+                password.data, password.size,
+                salt.data, salt.size,
+                iteration_count, counter);
+    } else if(enif_is_identical(argv[0], mod_st->atom_sha384)) {
+        return PBKDF2(sha384)(env,
+                password.data, password.size,
+                salt.data, salt.size,
+                iteration_count, counter);
+    } else if(enif_is_identical(argv[0], mod_st->atom_sha512)) {
+        return PBKDF2(sha512)(env,
+                password.data, password.size,
+                salt.data, salt.size,
+                iteration_count, counter);
+    } else {
+        return mk_error(env, "bad_hash");
+    }
+}
+
+static ErlNifFunc fastpbkdf2_nif_funcs[] = {
+    {"pbkdf2_block", 5, pbkdf2_nif}
+};
+
+ERL_NIF_INIT(fast_pbkdf2, fastpbkdf2_nif_funcs, load, reload, upgrade, unload);
diff --git a/mix.exs b/mix.exs
new file mode 100644
index 0000000..b581df4
--- /dev/null
+++ b/mix.exs
@@ -0,0 +1,18 @@
+defmodule Fast_Pbkdf2.MixProject do
+  use Mix.Project
+
+  def project do
+    [
+      app: :fast_pbkdf2,
+      version: "0.1.0",
+      elixir: "~> 1.10",
+      deps: deps()
+    ]
+  end
+
+  defp deps do
+    [
+      {:benchee, "~> 1.0", only: :dev}
+    ]
+  end
+end
diff --git a/mix.lock b/mix.lock
new file mode 100644
index 0000000..5aa28d0
--- /dev/null
+++ b/mix.lock
@@ -0,0 +1,4 @@
+%{
+  "benchee": {:hex, :benchee, "1.0.1", 
"66b211f9bfd84bd97e6d1beaddf8fc2312aaabe192f776e8931cb0c16f53a521", [:mix], 
[{:deep_merge, "~> 1.0", [hex: :deep_merge, repo: "hexpm", optional: false]}], 
"hexpm", "3ad58ae787e9c7c94dd7ceda3b587ec2c64604563e049b2a0e8baafae832addb"},
+  "deep_merge": {:hex, :deep_merge, "1.0.0", 
"b4aa1a0d1acac393bdf38b2291af38cb1d4a52806cf7a4906f718e1feb5ee961", [:mix], [], 
"hexpm", "ce708e5f094b9cd4e8f2be4f00d2f4250c4095be93f8cd6d018c753894885430"},
+}
diff --git a/rebar.config b/rebar.config
new file mode 100644
index 0000000..f98cd40
--- /dev/null
+++ b/rebar.config
@@ -0,0 +1,48 @@
+{deps, []}.
+
+{profiles, [
+  {test, [
+    {erl_opts, [debug_info, {d, 'STATISTICS'}]},
+    {deps, [
+      {statistics, {git, "https://github.com/NelsonVides/statistics.git";, 
{branch, "master"}}},
+      {base16, "1.0.0"},
+      {proper, "1.3.0"}
+     ]},
+    {plugins, [
+       {rebar3_codecov, {git, "https://github.com/esl/rebar3_codecov.git";, 
{ref, "6bd31cc"}}}
+     ]}
+   ]}
+ ]
+}.
+
+{plugins, [pc, rebar3_hex]}.
+
+{artifacts, ["priv/fast_pbkdf2.so"]}.
+
+{port_specs,
+ [
+    {
+        % Any arch
+        ".*",
+        % Create library
+        "priv/fast_pbkdf2.so",
+        % From files
+        ["c_src/*.c"],
+        % Using options
+        [ {env, [{"CFLAGS", "$CFLAGS -std=c99 -O3 -g -Wall -Wextra -fPIC"},
+                 {"LDLIBS", "$LDLIBS -lcrypto"},
+                 {"DRV_LINK_TEMPLATE", "$DRV_LINK_TEMPLATE $LDLIBS"}]}]
+     }
+ ]}.
+
+{provider_hooks,
+ [
+    {post,
+     [
+        {compile, {pc, compile}},
+        {clean, {pc, clean}}
+     ]}
+ ]}.
+
+{cover_enabled, true}.
+{cover_export_enabled, true}.
diff --git a/rebar.lock b/rebar.lock
new file mode 100644
index 0000000..57afcca
--- /dev/null
+++ b/rebar.lock
@@ -0,0 +1 @@
+[].
diff --git a/src/fast_pbkdf2.app.src b/src/fast_pbkdf2.app.src
new file mode 100644
index 0000000..c38c686
--- /dev/null
+++ b/src/fast_pbkdf2.app.src
@@ -0,0 +1,15 @@
+{application, fast_pbkdf2,
+ [{description, "Erlang's best pbkdf2 implementation"},
+  {vsn, "1.0.0"},
+  {registered, []},
+  {applications,
+   [kernel,
+    stdlib,
+    crypto
+   ]},
+  {env,[]},
+  {modules, []},
+  {licenses, ["Apache 2.0"]},
+  {links, [{"GitHub", "https://github.com/esl/fast_pbkdf2/"}]},
+  {exclude_files, ["c_src/fast_pbkdf2.d"]}
+ ]}.
diff --git a/src/fast_pbkdf2.erl b/src/fast_pbkdf2.erl
new file mode 100644
index 0000000..4583314
--- /dev/null
+++ b/src/fast_pbkdf2.erl
@@ -0,0 +1,51 @@
+-module(fast_pbkdf2).
+-on_load(load/0).
+
+-type sha_type() :: crypto:sha1() | crypto:sha2().
+
+-export([pbkdf2/4, pbkdf2/5]).
+
+%%% @doc
+%%% This function calculates the pbkdf2 algorithm where dkLen is simply 
assumed to be that of the
+%%% underlying hash function, a sane default.
+%%% @end
+-spec pbkdf2(sha_type(), binary(), binary(), non_neg_integer()) -> binary().
+pbkdf2(Hash, Password, Salt, IterationCount) ->
+    pbkdf2_block(Hash, Password, Salt, IterationCount, 1).
+
+%%% @doc
+%%% This function allows to customise the desired dkLen parameter for pbkdf2.
+%%% @end
+-spec pbkdf2(sha_type(), binary(), binary(), non_neg_integer(), 
non_neg_integer()) -> binary().
+pbkdf2(Hash, Password, Salt, IterationCount, DkLen) ->
+    pbkdf2(Hash, Password, Salt, IterationCount, DkLen, 1, [], 0).
+
+%%%===================================================================
+%%% Helper function
+%%%===================================================================
+pbkdf2(_Hash, _Password, _Salt, _IterationCount, DkLen, _BlockIndex, Acc, Len) 
when Len >= DkLen ->
+    Bin = iolist_to_binary(lists:reverse(Acc)),
+    binary:part(Bin, 0, DkLen);
+pbkdf2(Hash, Password, Salt, IterationCount, DkLen, BlockIndex, Acc, Len) ->
+    Block = pbkdf2_block(Hash, Password, Salt, IterationCount, BlockIndex),
+    pbkdf2(Hash, Password, Salt, IterationCount, DkLen, BlockIndex + 1, [Block 
| Acc], byte_size(Block) + Len).
+
+%%%===================================================================
+%%% NIF
+%%%===================================================================
+-spec pbkdf2_block(sha_type(), binary(), binary(), non_neg_integer(), 
non_neg_integer()) -> binary().
+pbkdf2_block(_Hash, _Password, _Salt, _IterationCount, _BlockSize) ->
+    erlang:nif_error(not_loaded).
+
+-spec load() -> any().
+load() ->
+    code:ensure_loaded(crypto),
+    PrivDir = case code:priv_dir(?MODULE) of
+                  {error, _} ->
+                      EbinDir = filename:dirname(code:which(?MODULE)),
+                      AppPath = filename:dirname(EbinDir),
+                      filename:join(AppPath, "priv");
+                  Path ->
+                      Path
+              end,
+    erlang:load_nif(filename:join(PrivDir, ?MODULE_STRING), none).
diff --git a/test/erl_pbkdf2.erl b/test/erl_pbkdf2.erl
new file mode 100644
index 0000000..fadc875
--- /dev/null
+++ b/test/erl_pbkdf2.erl
@@ -0,0 +1,36 @@
+-module(erl_pbkdf2).
+
+-export([pbkdf2_oneblock/4]).
+
+-type sha_type() :: crypto:sha1() | crypto:sha2().
+
+-spec pbkdf2_oneblock(sha_type(), binary(), binary(), non_neg_integer()) -> 
binary().
+pbkdf2_oneblock(Sha, Password, Salt, 1) ->
+    crypto_hmac(Sha, Password, <<Salt/binary, 0, 0, 0, 1>>);
+pbkdf2_oneblock(Sha, Password, Salt, IterationCount)
+  when is_integer(IterationCount), IterationCount > 1 ->
+    U1 = crypto_hmac(Sha, Password, <<Salt/binary, 0, 0, 0, 1>>),
+    mask(U1, iteration(Sha, Password, U1, IterationCount - 1)).
+
+-spec iteration(sha_type(), binary(), binary(), non_neg_integer()) -> binary().
+iteration(Sha, Password, UPrev, 1) ->
+    crypto_hmac(Sha, Password, UPrev);
+iteration(Sha, Password, UPrev, IterationCount) ->
+    U = crypto_hmac(Sha, Password, UPrev),
+    mask(U, iteration(Sha, Password, U, IterationCount - 1)).
+
+-spec mask(binary(), binary()) -> binary().
+mask(Key, Data) ->
+    KeySize = size(Key) * 8,
+    <<A:KeySize>> = Key,
+    <<B:KeySize>> = Data,
+    C = A bxor B,
+    <<C:KeySize>>.
+
+-if(?OTP_RELEASE >= 22).
+crypto_hmac(Sha, Bin1, Bin2) ->
+    crypto:mac(hmac, Sha, Bin1, Bin2).
+-else.
+crypto_hmac(Sha, Bin1, Bin2) ->
+    crypto:hmac(Sha, Bin1, Bin2).
+-endif.
diff --git a/test/pbkdf2_SUITE.erl b/test/pbkdf2_SUITE.erl
new file mode 100644
index 0000000..61fb712
--- /dev/null
+++ b/test/pbkdf2_SUITE.erl
@@ -0,0 +1,204 @@
+-module(pbkdf2_SUITE).
+
+%% API
+-export([all/0,
+         groups/0,
+         init_per_suite/1,
+         end_per_suite/1,
+         init_per_group/2,
+         end_per_group/2,
+         init_per_testcase/2,
+         end_per_testcase/2]).
+
+%% test cases
+-export([
+         erlang_and_nif_are_equivalent_sha1/1,
+         erlang_and_nif_are_equivalent_sha224/1,
+         erlang_and_nif_are_equivalent_sha256/1,
+         erlang_and_nif_are_equivalent_sha384/1,
+         erlang_and_nif_are_equivalent_sha512/1,
+         realtime_test/1
+        ]).
+-export([
+         test_vector_sha1_1/1,
+         test_vector_sha1_2/1,
+         test_vector_sha1_3/1,
+         test_vector_sha1_4/1,
+         test_vector_sha1_5/1,
+         test_vector_sha256_1/1,
+         test_vector_sha256_2/1,
+         test_vector_sha256_3/1,
+         test_vector_sha256_4/1,
+         test_vector_sha256_5/1,
+         test_vector_sha256_6/1
+        ]).
+
+-include_lib("common_test/include/ct.hrl").
+-include_lib("proper/include/proper.hrl").
+-include_lib("eunit/include/eunit.hrl").
+
+all() ->
+    [
+     {group, equivalents},
+     {group, test_vectors},
+     realtime_test
+    ].
+
+groups() ->
+    [
+     {equivalents, [parallel],
+      [
+       erlang_and_nif_are_equivalent_sha1,
+       erlang_and_nif_are_equivalent_sha224,
+       erlang_and_nif_are_equivalent_sha256,
+       erlang_and_nif_are_equivalent_sha384,
+       erlang_and_nif_are_equivalent_sha512
+      ]},
+     {test_vectors, [parallel],
+      [
+       test_vector_sha1_1,
+       test_vector_sha1_2,
+       test_vector_sha1_3,
+       test_vector_sha1_4,
+       test_vector_sha1_5,
+       test_vector_sha256_1,
+       test_vector_sha256_2,
+       test_vector_sha256_3,
+       test_vector_sha256_4,
+       test_vector_sha256_5,
+       test_vector_sha256_6
+      ]}
+    ].
+
+%%%===================================================================
+%%% Overall setup/teardown
+%%%===================================================================
+init_per_suite(Config) ->
+    Config.
+
+end_per_suite(_Config) ->
+    ok.
+
+%%%===================================================================
+%%% Group specific setup/teardown
+%%%===================================================================
+init_per_group(_Groupname, Config) ->
+    Config.
+
+end_per_group(_Groupname, _Config) ->
+    ok.
+
+%%%===================================================================
+%%% Testcase specific setup/teardown
+%%%===================================================================
+init_per_testcase(_TestCase, Config) ->
+    Config.
+
+end_per_testcase(_TestCase, _Config) ->
+    ok.
+
+%%%===================================================================
+%%% Individual Test Cases (from groups() definition)
+%%%===================================================================
+
+erlang_and_nif_are_equivalent_sha1(_Config) ->
+    erlang_and_nif_are_equivalent_(sha).
+
+erlang_and_nif_are_equivalent_sha224(_Config) ->
+    erlang_and_nif_are_equivalent_(sha224).
+
+erlang_and_nif_are_equivalent_sha256(_Config) ->
+    erlang_and_nif_are_equivalent_(sha256).
+
+erlang_and_nif_are_equivalent_sha384(_Config) ->
+    erlang_and_nif_are_equivalent_(sha384).
+
+erlang_and_nif_are_equivalent_sha512(_Config) ->
+    erlang_and_nif_are_equivalent_(sha512).
+
+erlang_and_nif_are_equivalent_(Sha) ->
+    Prop = ?FORALL({Pass, Salt, Count},
+                   {binary(), binary(), range(2,20000)},
+                   fast_pbkdf2:pbkdf2(Sha, Pass, Salt, Count)
+                       =:= erl_pbkdf2:pbkdf2_oneblock(Sha, Pass, Salt, Count)
+                  ),
+    ?assert(proper:quickcheck(Prop, [verbose, long_result,
+                                     {numtests, 100},
+                                     {start_size, 2},
+                                     {max_size, 64}])).
+
+
+%% Taken from the official RFC https://www.ietf.org/rfc/rfc6070.txt
+
+test_vector_sha1_1(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>,<<"salt">>,1,20,
+     base16:decode(<<"0c60c80f961f0e71f3a9b524af6012062fe037a6">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha, P, S, It, DkLen)).
+
+test_vector_sha1_2(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>,<<"salt">>,2,20,
+     base16:decode(<<"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha, P, S, It, DkLen)).
+
+test_vector_sha1_3(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>,<<"salt">>,4096,20,
+     base16:decode(<<"4b007901b765489abead49d926f721d065a429c1">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha, P, S, It, DkLen)).
+
+test_vector_sha1_4(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>,<<"salt">>,16777216,20,
+     base16:decode(<<"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha, P, S, It, DkLen)).
+
+test_vector_sha1_5(_Config) ->
+    {P,S,It,DkLen,Result} = 
{<<"passwordPASSWORDpassword">>,<<"saltSALTsaltSALTsaltSALTsaltSALTsalt">>,4096,25,
+     base16:decode(<<"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha, P, S, It, DkLen)).
+
+
+%% Taken from https://stackoverflow.com/a/5136918/8853275
+test_vector_sha256_1(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>, <<"salt">>, 1, 32,
+     
base16:decode(<<"120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha256, P, S, It, DkLen)).
+
+test_vector_sha256_2(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>, <<"salt">>, 2, 32,
+     
base16:decode(<<"ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c251dfd6e2d85a95474c43">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha256, P, S, It, DkLen)).
+
+test_vector_sha256_3(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>, <<"salt">>, 4096, 32,
+     
base16:decode(<<"c5e478d59288c841aa530db6845c4c8d962893a001ce4e11a4963873aa98134a">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha256, P, S, It, DkLen)).
+
+test_vector_sha256_4(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"password">>, <<"salt">>, 16777216, 32,
+     
base16:decode(<<"cf81c66fe8cfc04d1f31ecb65dab4089f7f179e89b3b0bcb17ad10e3ac6eba46">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha256, P, S, It, DkLen)).
+
+test_vector_sha256_5(_Config) ->
+    {P,S,It,DkLen,Result} = 
{<<"passwordPASSWORDpassword">>,<<"saltSALTsaltSALTsaltSALTsaltSALTsalt">>,4096,40,
+      
base16:decode(<<"348c89dbcbd32b2f32d814b8116e84cf2b17347ebc1800181c4e2a1fb8dd53e1c635518c7dac47e9">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha256, P, S, It, DkLen)).
+
+test_vector_sha256_6(_Config) ->
+    {P,S,It,DkLen,Result} = {<<"pass\0word">>, <<"sa\0lt">>, 4096, 16,
+     base16:decode(<<"89b69d0516f829893c696226650a8687">>)},
+    ?assertEqual(Result, fast_pbkdf2:pbkdf2(sha256, P, S, It, DkLen)).
+
+
+-ifdef(STATISTICS).
+realtime_test(_Config) ->
+    % Allocate two large binaries
+    A = crypto:strong_rand_bytes(64),
+    B = crypto:strong_rand_bytes(64),
+    Fun = fun() ->
+                  fast_pbkdf2:pbkdf2(512, A, B, 10000)
+          end,
+    #{mean := AverageJitter} = stats_latency:realtime_latency_on_load(Fun, 20, 
5000),
+    ?assert(AverageJitter < 50).
+-else.
+realtime_test(_Config) ->
+    ok.
+-endif.

Reply via email to