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

https://github.com/devall-org/feistel_cipher

First Post!

garrison

garrison

Implementing the cipher in SQL is equal parts horrifying and brilliant. I see it comes right from the Postgres wiki so I won’t argue with that!

In the example it looks like the sequential id is stored but the random id is the one used as the primary key. Am I understanding that correctly? If so you are losing all of the benefits of a sequential primary key, no?

Also, I think providing a default salt is a dangerous footgun. Force the user to generate a random salt (like Phoenix’s secret_key_base).

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

Where Next?

Popular in Announcing Top

Qqwy
Hello everyone, I wrote a small library today called MapDiff. It returns a map listing the (smallest amount of) changes to get from map...
New
wmnnd
Hi there, for my project DBLSQD, I needed a file storage solution that is a bit more flexible than Arc. Because I thought others might f...
New
mbuhot
Leverage Open Api 3.0 (Swagger) to document, test, validate and explore your Plug and Phoenix APIs. Generate and serve a JSON Open API ...
New
Qqwy
TypeCheck: Fast and flexible runtime type-checking for your Elixir projects. Core ideas Type- and function specifications are const...
336 14713 100
New
benlime
LiveMotion enables high performance animations declared on the server and run on the client. As a follow up to my previous thread A libr...
New
MRdotB
I needed to reuse React components from my Chrome extension in my Phoenix/LiveView backend. I noticed that for Svelte/Vue, there are live...
New
markmark206
simple_feature_flags is a tiny package that lets you turn features on or off based on which environment (e.g. localhost, staging, product...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44608 311
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement