gfc64 0.1.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9d7c2a4aaef604ecbe6d4c432f001bae3122383ab3c7e0d3e588db43b075da7a
4
- data.tar.gz: 11d79c4899212011f01b93b2d1b86c7663b84cdb73184817aa997fb6988a1f05
3
+ metadata.gz: 8dfb67644775ce35397c3704607242e328110ab480872792c0872fc490769c82
4
+ data.tar.gz: 5c834f1da177987712dca4022b7dcdac52f31e286028705d34e1092bd8106951
5
5
  SHA512:
6
- metadata.gz: dab37bcb93e364b9dcd98d1004e2b0c1bc7c62ad8d44650d3aedc80093564449972e8e1e1c550083baee464cd02bf7a6241a9cfa921fc5b771fbbe9c0c81c185
7
- data.tar.gz: dba7ac573a35f604bc7ebb4d82e82d76becd983799318d5e1eda6a6cb867b5367adfbde0fa9dabead075299bd5e5d7c1611b61bf86559cacec4f641a337b589d
6
+ metadata.gz: fe95cd567711b6817a99af0277ff48c61c50973f83e3539b9cb7432dd28ba4de40258df0f0da5555097b9a05b1d3d60201f8d7d50802076721993e31a39e9314
7
+ data.tar.gz: 2270b3a1b40681ed76d332c55b6f7025ae95cccfd7f1e9cf3792f8a84b11343242861172ee833f11c4964340500ca394dd75b08524840da7f6faa3dba5789979
data/CHANGELOG.md ADDED
@@ -0,0 +1,60 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0
4
+
5
+ ### Added
6
+
7
+ - `check: true` on formats (Crockford32, or any alphabet whose size is a
8
+ power of two from 4 to 256): one extra character from the alphabet that
9
+ catches every single wrong character and every swap of neighbours
10
+ (Damm's algorithm over GF(2^k)). A mismatch raises
11
+ `GFC64::Format::Alphabet::CheckError`. `Format#code_length` and
12
+ `Format#check?`.
13
+ - `group:` takes a list of sizes, e.g. `group: [4, 5]` for `XXXX-XXXXX`.
14
+
15
+ - `sql/gfc64_postgres.sql` (experimental): FF1 and Crockford base32 in
16
+ PL/pgSQL on pgcrypto, and a `BEFORE INSERT` trigger that fills a code
17
+ column from the row's primary key, giving the same codes as `has_code`
18
+ for any insert path. RDS-compatible. Specs (with `GFC64_PG_URL`) run the
19
+ NIST FF1 samples in SQL and compare it with the gem.
20
+
21
+ ## 1.0.0
22
+
23
+ ### Upgrading from 0.1.0
24
+
25
+ - 64-bit values are unchanged: the same key gives the same numbers.
26
+ - **Example and non-random keys now raise `ArgumentError`:** the README's
27
+ old example key, NIST's FF1 test keys, and keys of one or two repeated
28
+ bytes. Generate a key with `GFC64.generate_key`, or pass
29
+ `insecure_test_key: true` in tests.
30
+ - `GFC64::ActiveRecord` (`include GFC64::ActiveRecord[gfc]`) still works but
31
+ is deprecated in favor of `has_public_id`; `has_public_id tweak: false`
32
+ with the same key gives the same numbers. `find_gfc` now accepts the
33
+ String from `params` and raises `ActiveRecord::RecordNotFound` for bad
34
+ values instead of `ArgumentError`.
35
+
36
+ ### Added
37
+
38
+ - `bits:`: encrypt integers of any even width from 16 to 64 (10 rounds by
39
+ default below 64 bits).
40
+ - `tweak:`: independent mappings under one key (e.g. per model).
41
+ - `GFC64::FF1`: NIST SP 800-38G FF1 for AES-128/192/256, radix 2 to
42
+ 65,536, with tweaks; passes all nine NIST FF1 sample vectors.
43
+ - `GFC64::Format`: fixed-length codes in Crockford base32, base58, decimal
44
+ or any alphabet, with forgiving decoding where the alphabet allows it,
45
+ `normalize`, `canonical?` and `decode(strict: true)`.
46
+ - `GFC64.generate_key` and `GFC64::FF1.generate_key`.
47
+ - Rails helpers, on every model:
48
+ - `has_public_id`: computed public ids (`to_param`,
49
+ `find_by_public_id!`), per-model tweaks, prefixes, strict lookups,
50
+ `canonical_public_id`, and opt-in `guard_find`.
51
+ - `has_code`: a code made from the record's primary key (or a separate
52
+ sequence) and stored in a column, with `find_by_code!`,
53
+ `normalize_code` and `code_sequence_value`.
54
+ - One app-wide key from `GFC64.configure` or `GFC64_KEY`, read on first
55
+ use.
56
+
57
+ ## 0.1.0
58
+
59
+ - `GFC64.new(key)`: a Feistel cipher over 64-bit integers, and the
60
+ `GFC64::ActiveRecord` mixin.
data/README.md CHANGED
@@ -1,29 +1,54 @@
1
1
  # GFC64
2
2
 
3
- Encrypt 64-bit integers into other 64-bit integers without collisions.
3
+ Turn sequential database IDs into short, unguessable codes, and back
4
+ again, without storing anything extra.
4
5
 
5
- Useful for hiding database auto-incrementing primary keys without needing
6
- to store additional data (like a UUID field).
7
-
8
- For example, say you have a web app where routes are stored like `/customers/:id`
9
- so that you have exposed URL paths like this:
6
+ Say your app has URLs like these, which tell anyone how many customers you
7
+ have and invite guessing the next one:
10
8
 
11
9
  `/customers/1`
12
10
 
13
11
  `/customers/2`
14
12
 
15
- With this gem, you can (at view-time) encrypt the above IDs into different IDs
16
- so that you get these paths instead, without storing any additional data:
13
+ With this gem the same records get paths like these instead, while the
14
+ database keeps its ordinary auto-incrementing IDs and indexes:
15
+
16
+ `/customers/BQZbwjf` (the app decodes this back to customer 1)
17
17
 
18
- `/customers/4552956331295818987` (the backend decrypts this into `/customers/1`)
18
+ `/customers/F5WTxhS` (customer 2)
19
19
 
20
- `/customers/3833777695217202560` (the backend decrypts this into `/customers/2`)
20
+ ```ruby
21
+ class Customer < ApplicationRecord
22
+ has_public_id bits: 40, format: GFC64::Format::Base58.new(bits: 40)
23
+ end
24
+
25
+ customer_path(customer) # => "/customers/BQZbwjf"
26
+ Customer.find_by_public_id!(params[:id]) # => customer 1 (or a 404)
27
+ ```
28
+
29
+ The same goes for codes people read aloud and type, such as invoice numbers:
30
+
31
+ ```ruby
32
+ class Invoice < ApplicationRecord
33
+ has_public_id cipher: :ff1, prefix: "APP-",
34
+ format: GFC64::Format::Crockford32.new(length: 8, group: 4)
35
+ end
36
+
37
+ invoice.public_id # => "APP-TCNH-R99B"
38
+ Invoice.find_by_public_id!("app tcnh r99b") # any case or spacing
39
+ ```
21
40
 
22
- All while keeping your auto-incrementing, sequential IDs in your database and
23
- getting all the benefits of a standard database index.
41
+ (When a code must never change once issued, `has_code` stores it instead;
42
+ see [Computed or stored?](#computed-or-stored).)
24
43
 
25
- The encryption is achieved by implementing a format-preserving
26
- [Generalized Feistel Cipher][paper].
44
+ Under the hood, each number is encrypted with a secret key into another
45
+ number of the same size: no two IDs ever share a code, and without the key
46
+ nobody can work out the next one. Two ciphers are included: NIST's
47
+ [FF1][sp800-38g] format-preserving cipher, and a [Generalized Feistel
48
+ Cipher][paper] over 16 to 64-bit integers. The codes come from formatters
49
+ for [Crockford base32][crockford], base58, digits, or your own alphabet.
50
+
51
+ (The example codes above are illustrations; yours depend on your key.)
27
52
 
28
53
  ## Installation
29
54
 
@@ -33,58 +58,469 @@ Add to your `Gemfile`:
33
58
  gem "gfc64"
34
59
  ```
35
60
 
61
+ ## Rails Usage
62
+
63
+ Every ActiveRecord model gets two class methods: `has_public_id` (a code
64
+ computed from the primary key whenever it's needed, nothing stored) and
65
+ `has_code` (a code made once from the id and stored in a column).
66
+ Outside Rails, `include GFC64::Model`.
67
+
68
+ ### The key
69
+
70
+ Set it once; it's read the first time it's needed, so asset builds and
71
+ consoles without the secret still boot:
72
+
73
+ ```ruby
74
+ # config/initializers/gfc64.rb, or nothing at all to use ENV["GFC64_KEY"]
75
+ GFC64.configure { |c| c.key = Rails.application.credentials.gfc64_key }
76
+ ```
77
+
78
+ The key is 64 hex characters from `GFC64.generate_key`; use a different one
79
+ per environment and keep it. A missing key raises `GFC64::KeyMissing` naming
80
+ the setting.
81
+
82
+ ### Computed codes and public ids (`has_public_id`)
83
+
84
+ ```ruby
85
+ class Customer < ApplicationRecord
86
+ has_public_id bits: 40, format: GFC64::Format::Base58.new(bits: 40)
87
+ end
88
+
89
+ customer_path(customer) # => "/customers/BQZbwjf"
90
+ customer.public_id # => "BQZbwjf"
91
+
92
+ # app/controllers/customers_controller.rb
93
+ @customer = Customer.find_by_public_id!(params[:id])
94
+ ```
95
+
96
+ - `find_by_public_id!` raises `ActiveRecord::RecordNotFound` (so a 404) for
97
+ anything that isn't a valid id: wrong characters or length, out of range,
98
+ or no such record. `find_by_public_id` returns nil instead.
99
+ - Each model gets its own mapping (the tweak defaults to the table name), so
100
+ Customer 5 and Order 5 have unrelated public ids.
101
+ - `bits:` must cover your largest id (40 bits is about 1.1 trillion). Leave
102
+ out `format:` for a plain encrypted number (64-bit by default, as in
103
+ 0.1.0), or pass `cipher: :ff1` with a `length:`-based format.
104
+ - `prefix:` puts text in front (`"INV-"`); it's optional when decoding, in
105
+ any case or spacing. With FF1 and Crockford base32 that makes
106
+ invoice-style codes from the primary key with nothing stored:
107
+
108
+ ```ruby
109
+ has_public_id cipher: :ff1, prefix: "INV-",
110
+ format: GFC64::Format::Crockford32.new(length: 8, group: 4)
111
+ # invoice.public_id => "INV-TCNH-R99B"
112
+ ```
113
+ - `param: false` keeps `to_param` as the plain id.
114
+ - `guard_find: true` makes `find` raise `GFC64::UnsafeFind` when it's given
115
+ a String that isn't all digits, on the model, its relations and its
116
+ associations (see [Things to know](#things-to-know) for why). It's off by
117
+ default because it overrides `find`.
118
+ - Lookups are forgiving by default. Pass `strict: true` to accept only the
119
+ exact canonical form (`find_by_public_id!(value, strict: true)`), and use
120
+ `canonical_public_id(value)` to get that form.
121
+
122
+ To keep one URL per record while still accepting codes typed by hand,
123
+ redirect to the canonical form:
124
+
125
+ ```ruby
126
+ def show
127
+ @invoice = Invoice.find_by_public_id!(params[:id])
128
+ redirect_to @invoice, status: :moved_permanently unless params[:id] == @invoice.to_param
129
+ end
130
+ ```
131
+
132
+ ### Computed or stored?
133
+
134
+ `has_public_id` is the default choice: nothing extra in the database, and
135
+ any code decodes straight back to its record. The trade-off is that a code
136
+ depends on the key, format, prefix and tweak staying the same: change one
137
+ and every code changes with it.
138
+
139
+ Use `has_code` to store the code when it must never change once it's been
140
+ issued:
141
+
142
+ - it's printed or sent somewhere you can't update (invoices, receipts,
143
+ tickets, a payment provider's records);
144
+ - people read it outside your app (reports, CSV exports, SQL, support
145
+ tools) without the key;
146
+ - some codes come from elsewhere (imported or hand-entered) and must live
147
+ in the same column;
148
+ - you want the option of a new key or format for future records, with old
149
+ codes still valid.
150
+
151
+ ### Stored codes (`has_code`)
152
+
153
+ For codes that must never change once issued (see above). The code is made
154
+ from the record's own auto-incremented id, like `has_public_id`, and then
155
+ kept in a column:
156
+
157
+ ```ruby
158
+ # migration: one column, no sequence or counter
159
+ add_column :invoices, :number, :string, null: false
160
+ add_index :invoices, :number, unique: true
161
+
162
+ class Invoice < ApplicationRecord
163
+ has_code :number, prefix: "APP-",
164
+ format: GFC64::Format::Crockford32.new(length: 8, group: 4)
165
+ end
166
+
167
+ invoice = Invoice.create!(...)
168
+ invoice.number # => "APP-TCNH-R99B"
169
+ Invoice.find_by_code!(:number, "app tcnh-r99b") # any case or spacing, O/I/L, prefix optional
170
+ invoice.code_sequence_value(:number) # => invoice.id (decrypted from the code)
171
+ Invoice.normalize_code(:number, "app tcnh r99b") # => "APP-TCNH-R99B"
172
+ ```
173
+
174
+ `find_by_code(..., strict: true)` accepts only the stored form.
175
+
176
+ - On create the id is encrypted with FF1 (any alphabet; `cipher: :feistel`
177
+ for power-of-two ones), formatted, prefixed and stored. A code that's
178
+ already set is kept, and an id you set yourself is used.
179
+ - On Postgres the id is read ahead from the table's own sequence, so the
180
+ code goes into the same INSERT and the column can be `NOT NULL`. On other
181
+ databases the code is filled in right after the INSERT, in the same
182
+ transaction, so the column has to allow NULL.
183
+ - Reading the id ahead is safe under concurrency: `nextval` hands each
184
+ value out exactly once, and the INSERT supplies it as the id, so the
185
+ table's sequence still advances once per record.
186
+ - Codes are assigned by ActiveRecord callbacks, so `create` and `save` set
187
+ them but `insert_all`, `upsert_all` and raw SQL don't. For bulk inserts,
188
+ reserve ids from the sequence and set the column yourself with
189
+ `Invoice.generate_code(:number, id)`.
190
+ - Stored codes never change, even if you later change the format or key:
191
+ existing records keep theirs.
192
+ - The code is assigned in `before_create`, after validations, so validate
193
+ it in the database (`null: false`, unique index) rather than with
194
+ `validates :number, presence: true`.
195
+ - For numbering that's independent of the id, pass `sequence:` a Postgres
196
+ sequence name (`execute "CREATE SEQUENCE invoice_numbers"`) or a callable
197
+ returning the next Integer. Either way, a value used by a transaction
198
+ that rolls back is skipped, so codes can have gaps.
199
+ - The tweak defaults to `"table.column"`, so a stored code never matches
200
+ the same record's `has_public_id`, and two coded columns never share a
201
+ mapping.
202
+
203
+ ### Upgrading from `GFC64::ActiveRecord`
204
+
205
+ The 0.1.0 mixin (`include GFC64::ActiveRecord[gfc]`, `find_gfc`) still works
206
+ and now accepts the String from `params` (bad values raise `RecordNotFound`
207
+ instead of `ArgumentError`). It's deprecated in favor of `has_public_id`. To
208
+ keep the URLs you already have, set the same key with `GFC64.configure` (it
209
+ must be 64 hex characters, as `SecureRandom.hex(32)` made) and
210
+ use `has_public_id tweak: false`: no format, 64 bits and no tweak give the
211
+ same numbers as the old mixin.
212
+
36
213
  ## General Usage
37
214
 
215
+ Outside Rails (or for anything the Rails helpers don't cover), use the
216
+ ciphers and formatters directly.
217
+
218
+ **1. Make a key once and keep it secret.** Store it like any other
219
+ credential (an environment variable, Rails credentials, a secrets manager),
220
+ one per environment:
221
+
222
+ ```ruby
223
+ require "gfc64"
224
+
225
+ GFC64.generate_key # => "9b1f0c…" (64 hex characters; run once, then store it)
226
+ key = ENV.fetch("GFC64_KEY")
227
+ ```
228
+
229
+ **2. Short codes, e.g. order numbers.** FF1 encrypts a counter into 8
230
+ base-32 digits, and Crockford base32 writes them out:
231
+
232
+ ```ruby
233
+ orders = GFC64::FF1.new([key].pack("H*"), radix: 32, length: 8, tweak: "orders")
234
+ codes = GFC64::Format::Crockford32.new(length: 8, group: 4)
235
+
236
+ number = codes.encode(orders.encrypt(1042)) # => e.g. "F4CP-ZTDP"
237
+ orders.decrypt(codes.decode("f4cp ztdp")) # => 1042 (any case and spacing)
238
+
239
+ codes.valid?("F4CP-ZTDU") # => false (U isn't in the alphabet)
240
+ codes.decode("F4CP-ZTD") # raises ArgumentError (7 characters)
241
+ ```
242
+
243
+ **3. Public ids in URLs.** The Feistel cipher at 40 bits, shown in base58:
244
+
245
+ ```ruby
246
+ customers = GFC64.new(key, bits: 40, tweak: "customers")
247
+ ids = GFC64::Format::Base58.new(bits: 40)
248
+
249
+ ids.encode(customers.encrypt(1)) # => e.g. "MFNmYL5"
250
+ customers.decrypt(ids.decode("MFNmYL5")) # => 1
251
+ ```
252
+
253
+ **4. Full 64-bit integers** (what 0.1.0 did):
254
+
38
255
  ```ruby
39
- key = SecureRandom.hex(32) # => "ffb5e3600fc27924f97dc055440403b10ce97160261f2a87eee576584cf942e5"
40
256
  gfc = GFC64.new(key)
41
- gfc.encrypt(1) # => 4552956331295818987
42
- gfc.decrypt(4552956331295818987) # => 1
43
- gfc.encrypt(2) # => 3833777695217202560
44
- gfc.decrypt(3833777695217202560) # => 2
257
+ gfc.encrypt(1) # => e.g. 10372255740914870282
258
+ gfc.decrypt(10372255740914870282) # => 1
45
259
  ```
46
260
 
47
- ## Rails Usage
261
+ The outputs above depend on the key, so yours will differ. The sections
262
+ below cover each piece: keys, widths, tweaks, FF1 and the formats.
263
+
264
+ ## Keys
265
+
266
+ The key is what makes the output unpredictable. Two apps using the same
267
+ tweak (say `"invoices"`) get unrelated sequences as long as each has its
268
+ own random key; anyone who has a key can compute every value under it.
269
+
270
+ - Generate keys, don't write them: `GFC64.generate_key` (64 hex characters)
271
+ for `GFC64.new`, `GFC64::FF1.generate_key` (32 raw bytes, or
272
+ `generate_key(hex: true)`) for FF1. Never derive one from a password.
273
+ - Keep it with your other secrets (an env var, a secrets manager), one per
274
+ environment, and don't change it: a new key changes every value.
275
+ - The README's example key, NIST's FF1 test keys and keys that repeat one or
276
+ two bytes (`"k" * 32`, `""`) raise `ArgumentError`. Pass
277
+ `insecure_test_key: true` to use one in tests.
278
+ - If the key leaks, past and future values become computable. When values
279
+ must stay unguessable even then, use random values with a uniqueness check
280
+ instead of a cipher.
281
+
282
+ ### Upgrading from 0.1.0
283
+
284
+ 64-bit values are unchanged. The only difference is that the example key and
285
+ non-random keys now raise; generate a new key, or pass
286
+ `insecure_test_key: true` where a test relies on one.
287
+
288
+ ## Narrower numbers (`bits:`)
48
289
 
49
- For Rails, there's an ActiveRecord mixin which adds `#gfc_id` and
50
- `#to_param` methods and a `::find_gfc` class method. By setting `#to_param`,
51
- resource path helpers like `customer_path(@customer)` automatically use the
52
- GFC encrypted ID.
290
+ 64-bit results are long (up to 20 digits). For something people read and
291
+ type, such as an invoice or order number, encrypt into a narrower range
292
+ instead. `bits:` takes any even width from 16 to 64; every number from 0 to
293
+ `2**bits - 1` encrypts to a different number in that same range:
53
294
 
54
- Example usage:
295
+ ```ruby
296
+ gfc = GFC64.new(key, bits: 40)
297
+ gfc.encrypt(1) # => a number below 2**40 (1,099,511,627,776)
298
+ gfc.decrypt(gfc.encrypt(1)) # => 1
299
+ ```
300
+
301
+ 40 bits is exactly 8 characters of [Crockford base32][crockford], so a
302
+ counter can become a short, unguessable code like `7KQMR3XH`.
303
+
304
+ - Below 64 bits the default is 10 rounds (NIST's FF1 uses 10), since each
305
+ half is smaller; pass `rounds:` to change it. 64-bit keeps 3, so values
306
+ encrypted with 0.1.0 are unchanged.
307
+ - The width is mixed into the round keys: the same key at 40 and 48 bits
308
+ gives unrelated ciphers.
309
+ - Pick a width you can keep. Changing `bits:` (or the key) changes every
310
+ encrypted value, so store the encrypted value if it's printed or sent
311
+ anywhere, and start a new width for new records rather than re-encrypting
312
+ old ones.
313
+ - Small widths are small domains: at 16 bits there are only 65,536
314
+ values, so don't rely on unguessability there.
315
+
316
+ ## Tweaks (`tweak:`)
317
+
318
+ A tweak is a public string that picks one of many independent ciphers under
319
+ the same key, the way FF1 and other [tweakable block ciphers][tweakable]
320
+ use one:
55
321
 
56
322
  ```ruby
57
- # app/models/customer.rb
323
+ invoices = GFC64.new(key, bits: 40, tweak: "invoices")
324
+ orders = GFC64.new(key, bits: 40, tweak: "orders")
325
+ invoices.encrypt(42) # unrelated to orders.encrypt(42)
326
+ ```
58
327
 
59
- class Customer < ApplicationRecord
60
- include GFC64::ActiveRecord[GFC64.new(ENV['GFC_KEY'])]
61
- # or the argument can be a proc/lambda if you need late binding:
62
- # include GFC64::ActiveRecord[-> { GFC64.new(ENV['GFC_KEY']) }]
63
- end
328
+ - One secret key can serve several kinds of numbers, and knowing one kind's
329
+ codes says nothing about another's.
330
+ - A tweak isn't a secret and doesn't need randomness (that's the key's job),
331
+ and it isn't a per-record salt: values are only
332
+ guaranteed collision-free within one key + tweak. Use one fixed tweak per
333
+ kind of number.
334
+ - A new tweak (`"invoices-v2"`) starts a fresh sequence without a new key.
335
+ - No tweak gives exactly the results from before tweaks existed.
336
+
337
+ ## FF1 (`GFC64::FF1`)
338
+
339
+ [NIST SP 800-38G][sp800-38g] FF1 is the standard format-preserving cipher:
340
+ it encrypts a string of digits in any base (2 to 65,536) into another of the
341
+ same length and base, with AES and a tweak. This implementation passes all
342
+ nine of NIST's FF1 sample vectors (AES-128/192/256, radix 10 and 36, with and
343
+ without tweaks).
344
+
345
+ ```ruby
346
+ key = GFC64::FF1.generate_key # 32 random bytes (AES-256); generate_key(hex: true) for storage
347
+ ff1 = GFC64::FF1.new(key, radix: 32, length: 8, tweak: "invoices")
348
+ fmt = GFC64::Format::Crockford32.new(length: 8, group: 4)
349
+
350
+ code = fmt.encode(ff1.encrypt(42)) # => e.g. "N4WB-0TQ7"
351
+ ff1.decrypt(fmt.decode(code)) # => 42
64
352
  ```
65
353
 
66
- For retrieval, use `::find_gfc`:
354
+ - `radix:` doesn't have to be a power of two: a 31-character alphabet works
355
+ as `FF1.new(key, radix: 31, length: 8)` with
356
+ `Format::Alphabet.new(chars, length: 8)`.
357
+ - `encrypt_digits` / `decrypt_digits` work on digit arrays (most significant
358
+ first) of any length the standard allows, as in NIST's examples.
359
+ - SP 800-38G Rev. 1 requires at least 1,000,000 possible values
360
+ (`radix**length`); smaller domains are rejected.
361
+ - The key is raw bytes; from hex, `[hex].pack("H*")`.
362
+
363
+ ### Which to use
364
+
365
+ - **FF1** when you want a reviewed standard with published test vectors,
366
+ or a base that isn't a power of two. It takes about 0.1 ms per
367
+ value.
368
+ - **`GFC64` (the Feistel cipher)** for 64-bit IDs as in 0.1.0, or when
369
+ speed matters more than a standard. It's faster, but unreviewed (see the
370
+ disclaimer).
371
+
372
+ ## Formatting codes (`GFC64::Format`)
373
+
374
+ Encrypted numbers are easier to read, type and say aloud as short strings.
375
+ `GFC64::Format` turns a number of a given width into a fixed-length string
376
+ and back:
67
377
 
68
378
  ```ruby
69
- # app/controllers/customers_controller.rb
379
+ gfc = GFC64.new(key, bits: 40)
380
+ fmt = GFC64::Format::Crockford32.new(bits: 40, group: 4)
70
381
 
71
- class CustomersController < ApplicationController
72
- def show
73
- @customer = Customer.find_gfc(params[:id])
74
- end
75
- end
382
+ code = fmt.encode(gfc.encrypt(1)) # => "BGY8-1YKJ"
383
+ gfc.decrypt(fmt.decode(code)) # => 1
384
+ gfc.decrypt(fmt.decode("bgy8 lykj")) # => 1 (any case; O→0, I/L→1; spaces and hyphens ignored)
76
385
  ```
77
386
 
78
- ## Potential drawbacks
387
+ | Format | Example at 40 bits | Length at 40 bits | Good for |
388
+ |---|---|---|---|
389
+ | `Crockford32` | `BGY81YKJ` | 8 | reading aloud and typing: no I, L, O, U; forgiving input |
390
+ | `Base58` | `BQZbwjf` | 7 | links and QR codes: shortest, but case-sensitive |
391
+ | `Decimal` | `0396152076914` | 13 | phone keypads |
392
+ | `Alphabet` | yours | depends | any other set of characters |
393
+
394
+ - Codes are fixed-length (zero-padded), so a missing or extra character is
395
+ an error rather than a different number. `fmt.valid?(string)` checks
396
+ without raising.
397
+ - `decode` also rejects strings outside the width: not every 7-character
398
+ base58 string is a 40-bit number.
399
+ - How forgiving `decode` is depends on the format: Crockford32 ignores case
400
+ and reads O as 0 and I/L as 1, because none of those letters are in its
401
+ alphabet; Base58 is case-sensitive, because `a` and `A` are different
402
+ digits there. The rule is the same everywhere: only characters outside
403
+ the alphabet are remapped or ignored, so a typed variant can never turn
404
+ into a different valid code.
405
+ - `group:` and `separator:` only affect output; the separator, spaces and
406
+ hyphens are dropped on input (unless the alphabet uses them as digits).
407
+ - `group:` can also be a list of sizes: `group: [4, 5]` gives
408
+ `XXXX-XXXXX`; the last size repeats for anything longer.
409
+ - `check: true` adds one check character, taken from the alphabet itself
410
+ (for alphabets whose size is a power of two from 4 to 256, such as
411
+ Crockford32). It catches every single wrong character and every swap of
412
+ two neighbouring characters, so an app can say "that code has a typo"
413
+ without a lookup. `decode` then raises `GFC64::Format::Alphabet::CheckError`
414
+ (an `ArgumentError`). The check is Damm's algorithm over GF(2^k), not
415
+ Crockford's mod-37 check symbols (`*~$=U`), which are awkward in links
416
+ and read aloud. `fmt.length` stays the data length (what FF1 needs);
417
+ `fmt.code_length` counts the check character too.
418
+
419
+ ```ruby
420
+ fmt = GFC64::Format::Crockford32.new(length: 8, group: [4, 5], check: true)
421
+ fmt.encode(12345) # => "0000-0C1SW"
422
+ fmt.valid?("0000-0C1SX") # => false (typo)
423
+ ```
424
+ - `fmt.normalize("tcnh r99b")` returns the canonical form (`"TCNH-R99B"`
425
+ with `group: 4`), or nil when it isn't a code; `fmt.canonical?(string)`
426
+ checks for exactly that form.
427
+ - `fmt.decode(string, strict: true)` accepts only the canonical form, for
428
+ input that comes from machines (API clients, webhooks, signed links),
429
+ where any variation means a bug. Lenient is the default, for input from
430
+ people.
431
+ - Build your own with `GFC64::Format::Alphabet.new(chars, bits:,
432
+ case_sensitive:, aliases: { "O" => "0" })`.
433
+
434
+ ## Postgres (database-side codes)
435
+
436
+ *Experimental.* `sql/gfc64_postgres.sql` (shipped with the gem) is the same
437
+ FF1 and Crockford base32 in PL/pgSQL, plus a `BEFORE INSERT` trigger that
438
+ fills a code column from the row's primary key. It gives exactly the codes
439
+ `has_code` does, but for every insert path: `insert_all`, raw SQL, `COPY`,
440
+ `psql`, other services. It needs only `pgcrypto`, so it runs on Amazon RDS
441
+ and Aurora (no custom C extension).
442
+
443
+ Use it when rows are inserted outside ActiveRecord callbacks. If everything
444
+ goes through `create`/`save`, `has_code` alone is simpler and keeps the key
445
+ out of the database.
446
+
447
+ ```ruby
448
+ # migration
449
+ def up
450
+ execute File.read(File.join(Gem.loaded_specs["gfc64"].full_gem_path, "sql", "gfc64_postgres.sql"))
451
+ add_column :invoices, :number, :string, null: false
452
+ add_index :invoices, :number, unique: true
453
+ execute <<~SQL
454
+ CREATE TRIGGER invoices_number BEFORE INSERT ON invoices FOR EACH ROW
455
+ EXECUTE FUNCTION gfc64_assign_code('number', 'default', 'invoices.number', 'APP-', '8', '4');
456
+ SQL
457
+ end
458
+ ```
79
459
 
80
- Ruby's dynamic typing means we're just passing bare Integers around, so it's
81
- possible to make a mistake where you write something like `Model.find(gfc_id)`
82
- and return a completely unexpected record because you forgot to decrypt the ID.
460
+ ```sql
461
+ -- once per environment, from the same GFC64_KEY the app uses (not in a migration file)
462
+ INSERT INTO gfc64_keys VALUES ('default', decode('<the 64 hex characters>', 'hex'));
463
+ ```
83
464
 
84
- With a type system it would be trivial to prevent these errors. However, the
85
- space of 64-bit integers is very large, and encrypted IDs tend to occupy numbers
86
- much higher than most web apps will ever reach, so more than likely this sort of
87
- error would be discovered quickly as queries fail to find anything.
465
+ - **No race:** in a `BEFORE INSERT` trigger the id's default (`nextval`) has
466
+ already been applied, so the trigger encrypts the row's real id.
467
+ - **Arguments:** column, key name, tweak, prefix, length, group size, and
468
+ the primary-key column (`id` by default). The tweak must match the
469
+ model's: `has_code`'s default is `"table.column"`. A code that's already
470
+ set (by `has_code`, or by hand) is kept, so the two can run together.
471
+ - **Not yet in SQL:** `check: true` and lists of group sizes; the SQL
472
+ writes plain codes with one group size.
473
+ - **Functions** for use in SQL: `gfc64_ff1(key, tweak, radix, length,
474
+ value, decrypting)`, `gfc64_crockford_encode(value, length, group)` and
475
+ `gfc64_crockford_decode(text, length)` (forgiving, NULL for anything that
476
+ isn't a code; it doesn't strip prefixes).
477
+ - **Checked against the gem:** the spec suite (with `GFC64_PG_URL`) runs all
478
+ nine NIST FF1 samples in SQL and compares SQL codes with
479
+ `GFC64::FF1` + `Crockford32` and with the trigger's output.
480
+ - **Speed:** roughly 0.5 ms per row in the trigger; fine for normal inserts,
481
+ minutes for millions of rows.
482
+ - **The key lives in the database.** `gfc64_keys` is readable only by its
483
+ owner, and the trigger function reads it as `SECURITY DEFINER`, so the
484
+ app's role can insert but can't select the key. It's still in backups and
485
+ replicas, and readable by the owner role; that's the price of a trigger.
486
+
487
+ ## Things to know
488
+
489
+ - **A public id isn't permission.** It hides how many records you have and
490
+ in what order, and it can't be guessed, but anyone who has one can use
491
+ it: a forwarded email or a shared link carries it along. Check that the
492
+ current user may see the record, as you would for a plain id.
493
+ - **Never pass a public id to `find`.** Use `find_by_public_id!`, which
494
+ decodes it. `find` doesn't fail safely: ActiveRecord reads the leading
495
+ digits of a string as the id, so `Customer.find("7KQM-R3XH")` returns
496
+ customer 7, and a plain encrypted number at a narrow width (`bits: 24`
497
+ has only about 16.7 million values) can be a real id too. Either way it
498
+ quietly returns someone else's record. Two safety nets:
499
+ - a `prefix:` that starts with a letter (`"INV-"`): `find("INV-7KQM-R3XH")`
500
+ reads as 0 and finds nothing;
501
+ - `has_public_id ..., guard_find: true`: `find` raises `GFC64::UnsafeFind`
502
+ for any String that isn't all digits, so the mistake shows up as an
503
+ error in development and tests instead of a wrong record.
504
+
505
+ Neither covers `find_by(id: ...)` or `where(id: ...)`, which read leading
506
+ digits the same way, and the guard can't spot a public id that is itself
507
+ all digits (`has_public_id` without a `format:`).
508
+ - **The key is a single point of failure.** Lose it and computed codes can't
509
+ be decoded; leak it and every code, past and future, can be computed and
510
+ listed. Keep it with your other secrets, back it up, and see
511
+ [Keys](#keys). Codes stored with `has_code` keep working either way.
512
+ - **Computed codes change if the key, format, prefix or tweak changes,**
513
+ and old links and bookmarks stop working with them. Choose them once, or
514
+ store the codes; see [Computed or stored?](#computed-or-stored).
515
+ - **The width caps your ids.** `bits:` (or `radix**length` with FF1) is the
516
+ largest value that can be encoded; beyond it, encoding raises. 40 bits is
517
+ about 1.1 trillion, so pick a width with room to grow.
518
+ - **Computed codes aren't searchable in SQL.** There's no `LIKE 'TCNH%'`
519
+ and no sorting by code: look up a whole code (`find_by_public_id`), or
520
+ store the codes if people need to search them.
521
+ - **The Feistel cipher hasn't been reviewed;** FF1 is a NIST standard with
522
+ published test vectors. Use FF1 when you need a standard behind the
523
+ numbers ([Which to use](#which-to-use)).
88
524
 
89
525
  ## Disclaimer
90
526
 
@@ -104,4 +540,7 @@ Black, John, and Phillip Rogaway. ["Ciphers with Arbitrary Finite Domains."][pap
104
540
  Hat tip to [this Hacker News comment][hn] that led me to the idea and the paper.
105
541
 
106
542
  [paper]: https://web.cs.ucdavis.edu/~rogaway/papers/subset.pdf
543
+ [crockford]: https://www.crockford.com/base32.html
544
+ [tweakable]: https://people.csail.mit.edu/rivest/pubs/LRW02.pdf
545
+ [sp800-38g]: https://csrc.nist.gov/pubs/sp/800/38/g/r1/2pd
107
546
  [hn]: https://news.ycombinator.com/item?id=27016779