jechol

jechol

FeistelCipher, AshFeistelCipher - Encrypted integer IDs using Feistel cipher

I’m excited to share FeistelCipher and AshFeistelCipher, PostgreSQL-based libraries that provide encrypted integer IDs using the Feistel cipher algorithm.

The Problem

Sequential IDs (1, 2, 3…) expose sensitive business information:

  • Competitors can estimate your growth rate
  • Users can enumerate resources (/posts/1, /posts/2…)
  • Total record counts are revealed

Common solutions have their own issues:

  • UUIDs: Fixed 36 characters for everything - overkill for most use cases
  • Random integers: Collision risks and complex generation logic

Our Solution

FeistelCipher provides a different approach:

  • Store sequential integers internally
  • Expose encrypted integers externally (non-sequential, unpredictable)
  • Adjustable bit size per column: User ID = 40 bits, Post ID = 52 bits
  • Automatic encryption via PostgreSQL triggers

Key Features

  • Deterministic & Collision-free: One-to-one mapping within the bit range
  • Fast: ~4.4μs per encryption (benchmarked on Apple M3 Pro)

Usage

FeistelCipher (Ecto)

Migration:

defmodule MyApp.Repo.Migrations.CreatePosts do
  use Ecto.Migration

  def up do
    create table(:posts) do
      add :seq, :bigserial
      add :title, :string
    end

    execute FeistelCipher.up_for_trigger("public", "posts", "seq", "id")
  end

  def down do
    execute FeistelCipher.down_for_trigger("public", "posts", "seq", "id")
    drop table(:posts)
  end
end

Schema:

defmodule MyApp.Post do
  use Ecto.Schema

  schema "posts" do
    field :seq, :id, read_after_writes: true
    field :title, :string
  end
  
  @derive {Jason.Encoder, except: [:seq]}  # Hide seq in API responses
end

Usage:

%Post{title: "Hello"} |> Repo.insert()
# => %Post{id: 8234567, seq: 1, title: "Hello"}

The seq column auto-increments, and the trigger automatically encrypts it into the id column.

AshFeistelCipher (Ash Framework)

For Ash Framework users, AshFeistelCipher provides a cleaner, declarative syntax:

defmodule MyApp.Post do
  use Ash.Resource,
    data_layer: AshPostgres.DataLayer,
    extensions: [AshFeistelCipher]

  postgres do
    table "posts"
    repo MyApp.Repo
  end

  attributes do
    integer_sequence :seq
    encrypted_integer_primary_key :id, from: :seq
    
    attribute :title, :string, allow_nil?: false
  end
end

Run mix ash.codegen to generate migrations with automatic trigger configuration.

Links

Most Liked

jechol

jechol

Thank you for the excellent feedback! You’ve identified some important points that deserve clarification.

On Primary Key Performance Trade-offs

You’re absolutely right that using the encrypted id as a primary key loses the benefits of a sequential primary key. This is intentional - it’s the same trade-off that UUIDv4 has (random ordering causes B-tree page splits).

However, the library supports an alternative pattern: Keep id as a sequential primary key and encrypt a separate disp_id column for public display:

create table(:posts, primary_key: false) do
  add :id, :bigserial, primary_key: true    # Sequential, internal
  add :disp_id, :bigint                      # Encrypted, external
  add :title, :string
end

execute FeistelCipher.up_for_trigger("public", "posts", "id", "disp_id")

This gives you sequential PK performance while still hiding growth patterns externally.

Regarding encryption overhead: The encryption takes microseconds while typical INSERT/UPDATE operations involving disk writes (WAL, index updates) take milliseconds, making the encryption overhead negligible. For high-volume inserts or frequent sequential scans over large datasets, this library may not be the optimal choice.

This library targets typical web applications where security/privacy outweighs marginal insert/update performance. I’ve added a “Performance Considerations” section to the README to make these trade-offs explicit.

On Default Salt

You’re 100% correct - this is a security issue. Having all projects share the same default salt means analyzing one project’s encryption could compromise others.

I’ve just released v0.13.0 that automatically generates a unique random salt during installation. Each project now gets its own salt without any manual intervention.

Thanks again for taking the time to review this thoroughly!

jechol

jechol

I prefer systems with mathematical guarantees over probabilistic ones.

Random IDs require more bits to keep collision probability acceptable. Feistel’s collision-free guarantee allows fewer bits for human-friendly short IDs.

The deterministic nature also provides reproducible seed data with stable URLs, which random IDs can’t offer.

Regarding the Ecto Type approach: that would create a mismatch between DB values and URL values, making debugging with tools like TablePlus more difficult since you’d need to decrypt IDs to query the database.

pawoc50825

pawoc50825

This may be interesting to you, introduced just a month ago.

uuidv47.stateless.me

  • v7 in your DB, v4 on the wire
  • UUIDv7 is time-ordered → better index locality & pagination
  • façade hides timing patterns and looks like v4 to clients
  • uses a PRF (SipHash-2-4); avoids non-crypto hashes

github.com/stateless-me/uuidv47

byu

byu

Wouldn’t we still want/need a secondary index for disp_id to lookup – assuming growing number of rows – the record on an outside request?

So that’s still more work on top of the serial PK?

garrison

garrison

BTW UUIDs are not “36 characters”, they are 16 bytes. Nobody is storing the base16 encoding in the DB. It’s for humans.

Where Next?

Popular in Announcing Top

jarlah
Testcontainers Testcontainers is an Elixir library that supports ExUnit tests, providing lightweight, throwaway instances of common datab...
New
rodloboz
I’ve started working on a new library to run SQL queries and do basic business intelligence. Think “Blazer for Elixir.” Currently it fe...
New
halostatue
Enviable is a small collection of functions to make working with environment variables easier when configuring Elixir projects. It is des...
New
wingyplus
I just did a dirty hack after seeing Zoi on x.com a few hours ago. Quick Introduction The zoi_defstruct is a library to help you generat...
New
webofbits
Helix is a visual workflow designer for AI agents and multi-agent systems, built with Phoenix and React Flow. It provides an intuitive dr...
#ai
New
type1fool
WebAuthnLiveComponent WebAuthnComponents See this post about renaming the package. Passwordless authentication for Phoenix LiveView app...
New
waseigo
DiskSpace Hi everyone, I needed this for a project I’ve been working on, and couldn’t find a simple solution that would work. The solutio...
New
mudspot
Hi folks, I’d like to announce the release of Prometheus Agents, a set of subagents for Claude Code that cater to the Elixir Phoenix pro...
New
billylanchantin
The Explorer library has been out for some time. But we just released the latest version (see below), and we thought we’d start posting u...
New
trisolaran
Hi! :waving_hand: I would like to present LiveSelect, a little library that I wrote to easily add a dynamic selection input to your LV f...
194 10054 106
New

Other popular topics Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement