gfc64 0.0.3 → 1.0.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: 925a9e68e6edfd9f2d40a0e37f7712b56e113382a35f46ed6ff10319518e8bca
4
- data.tar.gz: 821817a8b6df2d28e61783676242e7ece64a868b764ce7a10defad2ad58ec6b2
3
+ metadata.gz: 5ba01573633ccbdf56b045cf0de1139a596db528c4847257bc00360f25109d06
4
+ data.tar.gz: 3232c6ab3bb1cf2d2ec3d0ddefe0a5f545905b9b71eb2310c1679233ab86936b
5
5
  SHA512:
6
- metadata.gz: a8f8f4055326bd37ae278fffbb3ae1f5ba04116dd949686df673fb03466c70da7eea23c31a9303a6b927da63e59d9b777c7fbfea4484cbc8eba03a0b3379d3b3
7
- data.tar.gz: 0a9a328a725f9fcd43fdf479e04eaca93f102facf2276a600d206c1369acc107ce94631d342cc92ebfd2e3e34a65d7a48eb310e3e046e6b3e334ce28c4c65c3f
6
+ metadata.gz: 291738356925c438cde0b580c81371b9ba0e8d94b92f116cfecde2c4f0dbc64cd5f2e7d0b00efb5f43bdaad80d037f280530de2b6cd2a5bad1d8b48e92e03911
7
+ data.tar.gz: 10504b1206ed91e5b4211d6c867efec038b6392c5fceb473dfd56991121ef13e8f89ea094fd3c892716fe5e1d34e9f1e6cb74104b27a7419ed50ace1865f0bf3
data/CHANGELOG.md ADDED
@@ -0,0 +1,42 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ ### Upgrading from 0.1.0
6
+
7
+ - 64-bit values are unchanged: the same key gives the same numbers.
8
+ - **Example and non-random keys now raise `ArgumentError`:** the README's
9
+ old example key, NIST's FF1 test keys, and keys of one or two repeated
10
+ bytes. Generate a key with `GFC64.generate_key`, or pass
11
+ `insecure_test_key: true` in tests.
12
+ - `GFC64::ActiveRecord` (`include GFC64::ActiveRecord[gfc]`) still works but
13
+ is deprecated in favor of `has_public_id`; `has_public_id tweak: false`
14
+ with the same key gives the same numbers. `find_gfc` now accepts the
15
+ String from `params` and raises `ActiveRecord::RecordNotFound` for bad
16
+ values instead of `ArgumentError`.
17
+
18
+ ### Added
19
+
20
+ - `bits:`: encrypt integers of any even width from 16 to 64 (10 rounds by
21
+ default below 64 bits).
22
+ - `tweak:`: independent mappings under one key (e.g. per model).
23
+ - `GFC64::FF1`: NIST SP 800-38G FF1 for AES-128/192/256, radix 2 to
24
+ 65,536, with tweaks; passes all nine NIST FF1 sample vectors.
25
+ - `GFC64::Format`: fixed-length codes in Crockford base32, base58, decimal
26
+ or any alphabet, with forgiving decoding where the alphabet allows it,
27
+ `normalize`, `canonical?` and `decode(strict: true)`.
28
+ - `GFC64.generate_key` and `GFC64::FF1.generate_key`.
29
+ - Rails helpers, on every model:
30
+ - `has_public_id`: computed public ids (`to_param`,
31
+ `find_by_public_id!`), per-model tweaks, prefixes, strict lookups,
32
+ `canonical_public_id`, and opt-in `guard_find`.
33
+ - `has_code`: a code made from the record's primary key (or a separate
34
+ sequence) and stored in a column, with `find_by_code!`,
35
+ `normalize_code` and `code_sequence_value`.
36
+ - One app-wide key from `GFC64.configure` or `GFC64_KEY`, read on first
37
+ use.
38
+
39
+ ## 0.1.0
40
+
41
+ - `GFC64.new(key)`: a Feistel cipher over 64-bit integers, and the
42
+ `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
+
18
+ `/customers/F5WTxhS` (customer 2)
19
+
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
17
36
 
18
- `/customers/4552956331295818987` (the backend decrypts this into `/customers/1`)
37
+ invoice.public_id # => "APP-TCNH-R99B"
38
+ Invoice.find_by_public_id!("app tcnh r99b") # any case or spacing
39
+ ```
19
40
 
20
- `/customers/3833777695217202560` (the backend decrypts this into `/customers/2`)
41
+ (When a code must never change once issued, `has_code` stores it instead;
42
+ see [Computed or stored?](#computed-or-stored).)
21
43
 
22
- All while keeping your auto-incrementing, sequential IDs in your database and
23
- getting all the benefits of a standard database index.
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.
24
50
 
25
- The encryption is achieved by implementing a format-preserving
26
- [Generalized Feistel Cipher][paper].
51
+ (The example codes above are illustrations; yours depend on your key.)
27
52
 
28
53
  ## Installation
29
54
 
@@ -33,58 +58,399 @@ 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
48
265
 
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.
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.
53
269
 
54
- Example usage:
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:`)
289
+
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:
55
294
 
56
295
  ```ruby
57
- # app/models/customer.rb
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
+ ```
58
300
 
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
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:
321
+
322
+ ```ruby
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)
64
326
  ```
65
327
 
66
- For retrieval, use `::find_gfc`:
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).
67
344
 
68
345
  ```ruby
69
- # app/controllers/customers_controller.rb
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)
70
349
 
71
- class CustomersController < ApplicationController
72
- def show
73
- @customer = Customer.find_gfc(params[:id])
74
- end
75
- end
350
+ code = fmt.encode(ff1.encrypt(42)) # => e.g. "N4WB-0TQ7"
351
+ ff1.decrypt(fmt.decode(code)) # => 42
76
352
  ```
77
353
 
78
- ## Potential drawbacks
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).
79
371
 
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.
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:
377
+
378
+ ```ruby
379
+ gfc = GFC64.new(key, bits: 40)
380
+ fmt = GFC64::Format::Crockford32.new(bits: 40, group: 4)
381
+
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)
385
+ ```
83
386
 
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.
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
+ - `fmt.normalize("tcnh r99b")` returns the canonical form (`"TCNH-R99B"`
408
+ with `group: 4`), or nil when it isn't a code; `fmt.canonical?(string)`
409
+ checks for exactly that form.
410
+ - `fmt.decode(string, strict: true)` accepts only the canonical form, for
411
+ input that comes from machines (API clients, webhooks, signed links),
412
+ where any variation means a bug. Lenient is the default, for input from
413
+ people.
414
+ - Build your own with `GFC64::Format::Alphabet.new(chars, bits:,
415
+ case_sensitive:, aliases: { "O" => "0" })`.
416
+
417
+ ## Things to know
418
+
419
+ - **A public id isn't permission.** It hides how many records you have and
420
+ in what order, and it can't be guessed, but anyone who has one can use
421
+ it: a forwarded email or a shared link carries it along. Check that the
422
+ current user may see the record, as you would for a plain id.
423
+ - **Never pass a public id to `find`.** Use `find_by_public_id!`, which
424
+ decodes it. `find` doesn't fail safely: ActiveRecord reads the leading
425
+ digits of a string as the id, so `Customer.find("7KQM-R3XH")` returns
426
+ customer 7, and a plain encrypted number at a narrow width (`bits: 24`
427
+ has only about 16.7 million values) can be a real id too. Either way it
428
+ quietly returns someone else's record. Two safety nets:
429
+ - a `prefix:` that starts with a letter (`"INV-"`): `find("INV-7KQM-R3XH")`
430
+ reads as 0 and finds nothing;
431
+ - `has_public_id ..., guard_find: true`: `find` raises `GFC64::UnsafeFind`
432
+ for any String that isn't all digits, so the mistake shows up as an
433
+ error in development and tests instead of a wrong record.
434
+
435
+ Neither covers `find_by(id: ...)` or `where(id: ...)`, which read leading
436
+ digits the same way, and the guard can't spot a public id that is itself
437
+ all digits (`has_public_id` without a `format:`).
438
+ - **The key is a single point of failure.** Lose it and computed codes can't
439
+ be decoded; leak it and every code, past and future, can be computed and
440
+ listed. Keep it with your other secrets, back it up, and see
441
+ [Keys](#keys). Codes stored with `has_code` keep working either way.
442
+ - **Computed codes change if the key, format, prefix or tweak changes,**
443
+ and old links and bookmarks stop working with them. Choose them once, or
444
+ store the codes; see [Computed or stored?](#computed-or-stored).
445
+ - **The width caps your ids.** `bits:` (or `radix**length` with FF1) is the
446
+ largest value that can be encoded; beyond it, encoding raises. 40 bits is
447
+ about 1.1 trillion, so pick a width with room to grow.
448
+ - **Computed codes aren't searchable in SQL.** There's no `LIKE 'TCNH%'`
449
+ and no sorting by code: look up a whole code (`find_by_public_id`), or
450
+ store the codes if people need to search them.
451
+ - **The Feistel cipher hasn't been reviewed;** FF1 is a NIST standard with
452
+ published test vectors. Use FF1 when you need a standard behind the
453
+ numbers ([Which to use](#which-to-use)).
88
454
 
89
455
  ## Disclaimer
90
456
 
@@ -104,4 +470,7 @@ Black, John, and Phillip Rogaway. ["Ciphers with Arbitrary Finite Domains."][pap
104
470
  Hat tip to [this Hacker News comment][hn] that led me to the idea and the paper.
105
471
 
106
472
  [paper]: https://web.cs.ucdavis.edu/~rogaway/papers/subset.pdf
473
+ [crockford]: https://www.crockford.com/base32.html
474
+ [tweakable]: https://people.csail.mit.edu/rivest/pubs/LRW02.pdf
475
+ [sp800-38g]: https://csrc.nist.gov/pubs/sp/800/38/g/r1/2pd
107
476
  [hn]: https://news.ycombinator.com/item?id=27016779
@@ -1,4 +1,8 @@
1
+ # frozen_string_literal: true
2
+
1
3
  class GFC64
4
+ # Deprecated: GFC64::Model (has_public_id / has_code) replaces this; it is
5
+ # kept so 0.1.0 apps keep working.
2
6
  module ActiveRecord
3
7
  def self.[](gfc)
4
8
  Module.new do
@@ -19,8 +23,13 @@ class GFC64
19
23
  @gfc ||= f_gfc.respond_to?(:call) ? f_gfc.call : f_gfc
20
24
  end
21
25
 
26
+ # Accepts the String from params; a bad or out-of-range value raises
27
+ # ActiveRecord::RecordNotFound (404) instead of ArgumentError (500).
22
28
  def find_gfc(gfc_id)
23
- find(gfc.decrypt(gfc_id))
29
+ id = gfc.decrypt(Integer(gfc_id.to_s, 10))
30
+ find(id)
31
+ rescue ArgumentError, TypeError
32
+ raise ::ActiveRecord::RecordNotFound, "Couldn't find #{name} with gfc id #{gfc_id.to_s[0, 64].inspect}"
24
33
  end
25
34
  end
26
35
 
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ class GFC64
4
+ # App-wide key for the Rails helpers (GFC64::Model). Read on first use, not
5
+ # at boot, so asset builds and consoles without the secret still start.
6
+ #
7
+ # GFC64.configure { |c| c.key = Rails.application.credentials.gfc64_key }
8
+ #
9
+ # Without configure, ENV["GFC64_KEY"] is used. The key is 64 hex
10
+ # characters (GFC64.generate_key): the Feistel cipher uses it as given,
11
+ # FF1 as the 32 bytes it encodes (AES-256).
12
+ class Config
13
+ attr_writer :key
14
+
15
+ def key
16
+ k = @key.respond_to?(:call) ? @key.call : @key
17
+ k = ENV["GFC64_KEY"] if k.nil? || k.empty?
18
+ if k.nil? || k.empty?
19
+ raise KeyMissing, "GFC64 has no key: set GFC64_KEY or GFC64.configure { |c| c.key = ... } " \
20
+ "(make one with GFC64.generate_key)"
21
+ end
22
+ unless k.match?(/\A\h{64}\z/)
23
+ raise ArgumentError, "the GFC64 key must be 64 hex characters (GFC64.generate_key)"
24
+ end
25
+
26
+ k
27
+ end
28
+
29
+ # Test-only escape hatch for published example keys (see GFC64::Keys).
30
+ attr_accessor :insecure_test_key
31
+ end
32
+
33
+ class KeyMissing < StandardError; end
34
+
35
+ def self.config
36
+ @config ||= Config.new
37
+ end
38
+
39
+ def self.configure
40
+ yield config
41
+ reset_ciphers!
42
+ config
43
+ end
44
+
45
+ # Ciphers are built once per model on first use; this drops them (after
46
+ # configure, or in tests that change the key).
47
+ def self.reset_ciphers!
48
+ @cipher_generation = cipher_generation + 1
49
+ end
50
+
51
+ def self.cipher_generation
52
+ @cipher_generation ||= 0
53
+ end
54
+ end