A zero-dependency Elixir Two-Factor Authentication (2FA) library built on Erlang's :crypto, with 100% API compatibility for nio_google_authenticator.

Features

  • Zero Runtime Dependencies — Pure Elixir RFC 6238 (TOTP) & RFC 4226 (HOTP) powered by Erlang :crypto
  • Drop-in API Compatibility — Same function names, options, and return tuples as nio_google_authenticator (Ex2FA & Ex2FA.Changeset)
  • Modern Security — Constant-time token comparison, SHA-1 / SHA-256 / SHA-512 support, and replay-attack protection (:since / :last_used_at / :last_step)
  • Standard Provisioning URIs — otpauth://totp/... and otpauth://hotp/... URIs (Ex2FA.otpauth_uri/3, Ex2FA.hotp_uri/4), while keeping Ex2FA.generate_url/3 for backward compatibility
  • Recovery / Backup Codes — Generate, SHA-256 hash, and validate single-use backup codes (Ex2FA.RecoveryCodes)
  • Optional Ecto 3 Integration — Ex2FA.Changeset is automatically compiled when :ecto is present in your project

Installation

Add ex_2fa to your list of dependencies in mix.exs:

def deps do
  [
    {:ex_2fa, "~> 0.1.0"}
  ]
end

Configuration

Optionally configure a default issuer:

config :ex_2fa, issuer: "MyApp"

Migration Tip: If :ex_2fa does not set :issuer, Ex2FA automatically falls back to config :nio_google_authenticator, issuer: "...".

Quick Start (nio_google_authenticator Compatible API)

# 1. Generate a Base32 secret (10 bytes / 16 chars by default, or pass byte length e.g. 20)
secret = Ex2FA.generate_secret()

# 2. Generate a provisioning URI for QR code rendering (recommended)
uri = Ex2FA.otpauth_uri(secret, "alice@example.com", issuer: "MyApp")
#=> "otpauth://totp/MyApp:alice%40example.com?secret=...&issuer=MyApp"

# Legacy Google Charts QR URL (compatible with nio_google_authenticator)
url = Ex2FA.generate_url(secret, "alice@example.com", "MyApp")

# 3. Generate a TOTP token (useful for tests)
token = Ex2FA.generate_token(secret)

# 4. Validate a TOTP token
Ex2FA.validate_token(secret, token)
#=> {:ok, :pass}

Ex2FA.validate_token(secret, token, token_length: 6, interval_length: 30, window: 1)
#=> {:ok, :pass}

Ex2FA.validate_token(secret, "000000")
#=> {:error, :invalid_token}

Replay Protection (TOTP)

Prevent a valid TOTP code from being reused within the same time step:

# Option A: Track last_step with verify_token/3
{:ok, step} = Ex2FA.verify_token(secret, token, window: 1)
# Persist `step` on the user record, then on the next login:
Ex2FA.verify_token(secret, token, window: 1, last_step: step)
#=> {:error, :invalid_token}

# Option B: Track last authentication timestamp with :since / :last_used_at
Ex2FA.validate_token(secret, token, since: user.totp_last_used_at)

HOTP (RFC 4226)

token = Ex2FA.generate_hotp(secret, 0)

# Validate at exact counter
{:ok, :pass} = Ex2FA.validate_hotp(secret, token, 0)

# Verify with look-ahead resynchronization window
{:ok, matched_counter} = Ex2FA.verify_hotp(secret, token, 0, window: 5)
# Store `matched_counter + 1` as the user's next expected counter

Recovery / Backup Codes

# Generate 10 human-friendly Crockford Base32 codes (e.g., "7K9M-2XPQ")
codes = Ex2FA.generate_recovery_codes()

# Hash codes with SHA-256 before saving to your database
hashed_codes = Ex2FA.RecoveryCodes.hash_all(codes)

# Validate and consume a single-use code (case-insensitive, ignores spaces/hyphens)
case Ex2FA.validate_recovery_code(user_input, hashed_codes) do
  {:ok, remaining_hashed_codes} ->
    # Persist remaining_hashed_codes and allow login
    :ok

  {:error, :invalid_code} ->
    :error
end

Ecto.Changeset Integration

When :ecto is installed in your application, Ex2FA.Changeset is available with the exact same API as NioGoogleAuthenticator.Changeset:

defmodule MyApp.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :name, :string
    field :ga_secret, :string
  end

  def changeset(user, params \\ %{}) do
    user
    |> cast(params, [:name, :ga_secret])
    |> Ex2FA.Changeset.add_secret_to_changeset()
  end

  def regenerate_2fa_changeset(user) do
    user
    |> change()
    |> Ex2FA.Changeset.regenerate_secret_in_changeset(:ga_secret)
  end
end

Migrating from nio_google_authenticator

nio_google_authenticatorex_2fa
NioGoogleAuthenticator.generate_secret/0Ex2FA.generate_secret/0
NioGoogleAuthenticator.generate_token/1Ex2FA.generate_token/1
NioGoogleAuthenticator.generate_url/2,3Ex2FA.generate_url/2,3 (or Ex2FA.otpauth_uri/3)
NioGoogleAuthenticator.validate_token/2,3Ex2FA.validate_token/2,3
NioGoogleAuthenticator.Changeset.add_secret_to_changeset/1,2Ex2FA.Changeset.add_secret_to_changeset/1,2
NioGoogleAuthenticator.Changeset.regenerate_secret_in_changeset/1,2Ex2FA.Changeset.regenerate_secret_in_changeset/1,2

Examples

Runnable example scripts are located in examples/:

mix run examples/totp_basic.exs
mix run examples/replay_protection.exs
mix run examples/hotp_resync.exs
mix run examples/recovery_codes.exs
mix run examples/nio_migration.exs

Testing & Fuzzing

Run the full ExUnit test suite (including RFC 4226 / RFC 6238 vectors and fuzz tests):

mix test

Run only the ExUnit fuzz suite with custom iterations and a reproducible seed:

FUZZ_ITERATIONS=2000 FUZZ_SEED=42 mix test --only fuzz

Run the standalone stress fuzzer:

mix run fuzz/run.exs --iterations 10000 --seed 42

License

MIT