gfc64 1.0.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: 5ba01573633ccbdf56b045cf0de1139a596db528c4847257bc00360f25109d06
4
- data.tar.gz: 3232c6ab3bb1cf2d2ec3d0ddefe0a5f545905b9b71eb2310c1679233ab86936b
3
+ metadata.gz: 8dfb67644775ce35397c3704607242e328110ab480872792c0872fc490769c82
4
+ data.tar.gz: 5c834f1da177987712dca4022b7dcdac52f31e286028705d34e1092bd8106951
5
5
  SHA512:
6
- metadata.gz: 291738356925c438cde0b580c81371b9ba0e8d94b92f116cfecde2c4f0dbc64cd5f2e7d0b00efb5f43bdaad80d037f280530de2b6cd2a5bad1d8b48e92e03911
7
- data.tar.gz: 10504b1206ed91e5b4211d6c867efec038b6392c5fceb473dfd56991121ef13e8f89ea094fd3c892716fe5e1d34e9f1e6cb74104b27a7419ed50ace1865f0bf3
6
+ metadata.gz: fe95cd567711b6817a99af0277ff48c61c50973f83e3539b9cb7432dd28ba4de40258df0f0da5555097b9a05b1d3d60201f8d7d50802076721993e31a39e9314
7
+ data.tar.gz: 2270b3a1b40681ed76d332c55b6f7025ae95cccfd7f1e9cf3792f8a84b11343242861172ee833f11c4964340500ca394dd75b08524840da7f6faa3dba5789979
data/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
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
+
3
21
  ## 1.0.0
4
22
 
5
23
  ### Upgrading from 0.1.0
data/README.md CHANGED
@@ -404,6 +404,23 @@ gfc.decrypt(fmt.decode("bgy8 lykj")) # => 1 (any case; O→0, I/L→1; spaces an
404
404
  into a different valid code.
405
405
  - `group:` and `separator:` only affect output; the separator, spaces and
406
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
+ ```
407
424
  - `fmt.normalize("tcnh r99b")` returns the canonical form (`"TCNH-R99B"`
408
425
  with `group: 4`), or nil when it isn't a code; `fmt.canonical?(string)`
409
426
  checks for exactly that form.
@@ -414,6 +431,59 @@ gfc.decrypt(fmt.decode("bgy8 lykj")) # => 1 (any case; O→0, I/L→1; spaces an
414
431
  - Build your own with `GFC64::Format::Alphabet.new(chars, bits:,
415
432
  case_sensitive:, aliases: { "O" => "0" })`.
416
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
+ ```
459
+
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
+ ```
464
+
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
+
417
487
  ## Things to know
418
488
 
419
489
  - **A public id isn't permission.** It hides how many records you have and
data/lib/gfc64/format.rb CHANGED
@@ -16,22 +16,45 @@ class GFC64
16
16
  class Alphabet
17
17
  attr_reader :alphabet, :bits, :length, :group, :separator
18
18
 
19
+ # Raised by decode when a code's check character doesn't match: a typo
20
+ # (any one wrong character, or two neighbours swapped), never a valid
21
+ # code. An ArgumentError, so valid? and normalize treat it like any
22
+ # other bad input.
23
+ class CheckError < ArgumentError; end
24
+
25
+ # Irreducible polynomials for GF(2^k), used by the check character.
26
+ GF_POLYNOMIALS = { 2 => 0b111, 3 => 0b1011, 4 => 0b10011, 5 => 0b100101, 6 => 0b1000011,
27
+ 7 => 0b10000011, 8 => 0b100011011 }.freeze
28
+
19
29
  # alphabet: the characters, lowest value first
20
30
  # bits: the width of the numbers (match GFC64's bits:), or
21
31
  # length: a fixed number of characters (match FF1's length:
22
32
  # when FF1's radix is this alphabet's size)
23
33
  # case_sensitive: false folds input to the alphabet's case
24
34
  # aliases: extra input characters read as another, e.g. "O" => "0"
25
- # group: on output, put `separator` every `group` characters
35
+ # group: on output, put `separator` every `group` characters,
36
+ # or an Array of group sizes, e.g. [4, 5] (the last
37
+ # size repeats for anything longer)
38
+ # check: true appends one check character (alphabets of 4 to
39
+ # 256 characters, a power of two). It catches every
40
+ # single wrong character and every swap of two
41
+ # neighbours, and it's from the alphabet itself.
26
42
  # ignore: input characters dropped before decoding (spaces and
27
43
  # hyphens by default; the separator always is)
28
- def initialize(alphabet, bits: nil, length: nil, case_sensitive: true, aliases: {}, group: nil, separator: "-", ignore: " -")
44
+ def initialize(alphabet, bits: nil, length: nil, case_sensitive: true, aliases: {}, group: nil, separator: "-", ignore: " -",
45
+ check: false)
29
46
  chars = alphabet.chars
30
47
  raise ArgumentError, "alphabet needs at least 2 distinct characters" if chars.uniq.size != chars.size || chars.size < 2
31
48
  raise ArgumentError, "give exactly one of bits: or length:" unless bits.nil? ^ length.nil?
32
49
  raise ArgumentError, "bits must be a positive Integer" unless bits.nil? || (bits.is_a?(Integer) && bits.positive?)
33
50
  raise ArgumentError, "length must be a positive Integer" unless length.nil? || (length.is_a?(Integer) && length.positive?)
34
- raise ArgumentError, "group must be a positive Integer" unless group.nil? || (group.is_a?(Integer) && group.positive?)
51
+ groups = group.is_a?(Array) ? group : [group].compact
52
+ unless groups.all? { |g| g.is_a?(Integer) && g.positive? } && (group.nil? || !groups.empty?)
53
+ raise ArgumentError, "group must be a positive Integer or an Array of them"
54
+ end
55
+ if check && !(chars.size & (chars.size - 1)).zero? || check && !GF_POLYNOMIALS.key?(chars.size.bit_length - 1)
56
+ raise ArgumentError, "check: needs an alphabet of 4 to 256 characters, a power of two (this one has #{chars.size})"
57
+ end
35
58
 
36
59
  @alphabet = alphabet.dup.freeze
37
60
  @chars = chars.freeze
@@ -47,7 +70,13 @@ class GFC64
47
70
  @bits = @max.bit_length
48
71
  end
49
72
  @case_sensitive = case_sensitive
50
- @group = group
73
+ @group = group.is_a?(Array) ? group.dup.freeze : group
74
+ @groups = groups.freeze
75
+ @check = check ? true : false
76
+ if @check
77
+ @gf_bits = @base.bit_length - 1
78
+ @gf_poly = GF_POLYNOMIALS.fetch(@gf_bits)
79
+ end
51
80
  @separator = separator
52
81
  dropped = (ignore.to_s + separator.to_s).chars.uniq - chars
53
82
  @ignore = dropped.empty? ? nil : /[#{Regexp.escape(dropped.join)}]/
@@ -72,8 +101,18 @@ class GFC64
72
101
  out[i] = @chars[digit]
73
102
  i -= 1
74
103
  end
75
- s = out.join
76
- group ? s.scan(/.{1,#{group}}/).join(separator) : s
104
+ out << @chars[check_digit(out.map { |c| @values[fold(c)] })] if @check
105
+ grouped(out.join)
106
+ end
107
+
108
+ # True when codes end in a check character.
109
+ def check?
110
+ @check
111
+ end
112
+
113
+ # Characters in a code, counting the check character but not separators.
114
+ def code_length
115
+ @length + (@check ? 1 : 0)
77
116
  end
78
117
 
79
118
  # strict: true accepts only the exact canonical form (what encode
@@ -106,14 +145,20 @@ class GFC64
106
145
  raise ArgumentError, "expected a String" unless string.is_a?(String)
107
146
 
108
147
  s = @ignore ? string.gsub(@ignore, "") : string
109
- raise ArgumentError, "expected #{@length} characters, got #{s.length}" unless s.length == @length
148
+ raise ArgumentError, "expected #{code_length} characters, got #{s.length}" unless s.length == code_length
110
149
 
111
- number = s.each_char.reduce(0) do |acc, c|
150
+ digits = s.each_char.map do |c|
112
151
  digit = @values[fold(c)]
113
152
  raise ArgumentError, "#{c.inspect} isn't a valid character" if digit.nil?
114
153
 
115
- acc * @base + digit
154
+ digit
155
+ end
156
+ if @check
157
+ raise CheckError, "#{string[0, 64].inspect} has a typo (its check character doesn't match)" unless damm(digits).zero?
158
+
159
+ digits.pop
116
160
  end
161
+ number = digits.reduce(0) { |acc, d| acc * @base + d }
117
162
  raise ArgumentError, "#{string.inspect} is out of range (above #{@max})" if number > @max
118
163
 
119
164
  number
@@ -140,18 +185,54 @@ class GFC64
140
185
  def fold(c)
141
186
  @case_sensitive ? c : c.upcase
142
187
  end
188
+
189
+ def grouped(s)
190
+ return s if @groups.empty?
191
+
192
+ parts = []
193
+ i = 0
194
+ k = 0
195
+ while i < s.length
196
+ size = @groups[[k, @groups.size - 1].min]
197
+ parts << s[i, size]
198
+ i += size
199
+ k += 1
200
+ end
201
+ parts.join(separator)
202
+ end
203
+
204
+ # Damm's algorithm over GF(2^k) with x * y = 2x + y: a weakly totally
205
+ # anti-symmetric quasigroup, so any one changed digit or swap of two
206
+ # neighbouring digits changes the result.
207
+ def damm(digits)
208
+ digits.reduce(0) { |acc, d| gf_double(acc) ^ d }
209
+ end
210
+
211
+ # The digit that brings the running Damm value to zero.
212
+ def check_digit(digits)
213
+ gf_double(damm(digits))
214
+ end
215
+
216
+ def gf_double(x)
217
+ x <<= 1
218
+ x ^= @gf_poly if x >= @base
219
+ x
220
+ end
143
221
  end
144
222
 
145
223
  # Douglas Crockford's base32 (https://www.crockford.com/base32.html):
146
224
  # digits and capitals without I, L, O, U. Input is forgiving: any case,
147
225
  # O reads as 0, I and L as 1, hyphens and spaces ignored. 40 bits is
148
226
  # exactly 8 characters.
227
+ #
228
+ # check: true adds a 9th character from the same 32 (not Crockford's own
229
+ # mod-37 check symbols *~$=U, which are awkward in links and to read out).
149
230
  class Crockford32 < Alphabet
150
231
  ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
151
232
 
152
- def initialize(bits: nil, length: nil, group: nil, separator: "-")
233
+ def initialize(bits: nil, length: nil, group: nil, separator: "-", check: false)
153
234
  super(ALPHABET, bits: bits, length: length, case_sensitive: false, aliases: { "O" => "0", "I" => "1", "L" => "1" },
154
- group: group, separator: separator)
235
+ group: group, separator: separator, check: check)
155
236
  end
156
237
  end
157
238
 
data/lib/gfc64.rb CHANGED
@@ -6,7 +6,7 @@ require "securerandom"
6
6
  # A balanced Feistel cipher over the integers 0...2**bits: every value maps to
7
7
  # exactly one other value of the same width, and back again with the same key.
8
8
  class GFC64
9
- VERSION = "1.0.0".freeze
9
+ VERSION = "1.1.0".freeze
10
10
 
11
11
  MIN_BITS = 16
12
12
  MAX_BITS = 64
@@ -0,0 +1,203 @@
1
+ -- gfc64 for Postgres: FF1 (NIST SP 800-38G) in PL/pgSQL on pgcrypto, Crockford
2
+ -- base32, and an INSERT trigger that fills a code column from the row's
3
+ -- primary key. Produces the same codes as the gem (GFC64::FF1 +
4
+ -- GFC64::Format::Crockford32, and has_code's default tweak "table.column").
5
+ --
6
+ -- Needs only CREATE EXTENSION pgcrypto, so it runs on Amazon RDS / Aurora.
7
+ -- Experimental: see "Postgres (database-side codes)" in the README.
8
+
9
+ CREATE EXTENSION IF NOT EXISTS pgcrypto;
10
+
11
+ -- ---- byte helpers ----------------------------------------------------------
12
+
13
+ -- Big-endian bytes of a non-negative integer, padded to len bytes.
14
+ CREATE OR REPLACE FUNCTION gfc64_num_to_bytes(n numeric, len int) RETURNS bytea
15
+ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE AS $$
16
+ DECLARE
17
+ out bytea;
18
+ BEGIN
19
+ IF len = 0 THEN RETURN ''::bytea; END IF;
20
+ out := decode(repeat('00', len), 'hex');
21
+ FOR i IN REVERSE len - 1..0 LOOP
22
+ out := set_byte(out, i, mod(n, 256)::int);
23
+ n := div(n, 256);
24
+ END LOOP;
25
+ RETURN out;
26
+ END $$;
27
+
28
+ CREATE OR REPLACE FUNCTION gfc64_bytes_to_num(b bytea) RETURNS numeric
29
+ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE AS $$
30
+ DECLARE
31
+ n numeric := 0;
32
+ BEGIN
33
+ FOR i IN 0..length(b) - 1 LOOP
34
+ n := n * 256 + get_byte(b, i);
35
+ END LOOP;
36
+ RETURN n;
37
+ END $$;
38
+
39
+ CREATE OR REPLACE FUNCTION gfc64_xor16(a bytea, b bytea) RETURNS bytea
40
+ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE AS $$
41
+ DECLARE
42
+ out bytea := a;
43
+ BEGIN
44
+ FOR i IN 0..15 LOOP
45
+ out := set_byte(out, i, get_byte(a, i) # get_byte(b, i));
46
+ END LOOP;
47
+ RETURN out;
48
+ END $$;
49
+
50
+ -- One AES block (the key's length picks AES-128/192/256).
51
+ CREATE OR REPLACE FUNCTION gfc64_aes(key bytea, block bytea) RETURNS bytea
52
+ LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
53
+ SELECT encrypt(block, key, 'aes-ecb/pad:none')
54
+ $$;
55
+
56
+ -- ---- FF1 -------------------------------------------------------------------
57
+
58
+ -- Encrypts (or decrypts) x, an integer of n digits in base radix, into another
59
+ -- of the same size. Digits are kept as one number per half, so NUM/STR from the
60
+ -- standard are just the numbers themselves.
61
+ CREATE OR REPLACE FUNCTION gfc64_ff1(key bytea, tweak bytea, radix int, n int, x numeric, decrypting boolean DEFAULT false)
62
+ RETURNS numeric
63
+ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE AS $$
64
+ DECLARE
65
+ u int := n / 2;
66
+ v int := n - u;
67
+ t int := length(tweak);
68
+ rv numeric := power(radix::numeric, v);
69
+ a numeric := div(x, rv);
70
+ b numeric := mod(x, rv);
71
+ bb int := 0; -- b in the standard: bytes for radix^v - 1
72
+ d int;
73
+ p bytea;
74
+ pad bytea;
75
+ q bytea;
76
+ r bytea;
77
+ s bytea;
78
+ y numeric;
79
+ m int;
80
+ rm numeric;
81
+ c numeric;
82
+ tmp numeric;
83
+ i int;
84
+ j int;
85
+ BEGIN
86
+ IF radix < 2 OR radix > 65536 THEN RAISE EXCEPTION 'radix must be 2 to 65536'; END IF;
87
+ IF n < 2 OR power(radix::numeric, n) < 1000000 THEN RAISE EXCEPTION 'radix^length must be at least 1,000,000'; END IF;
88
+ IF x < 0 OR x >= power(radix::numeric, n) THEN RAISE EXCEPTION 'value out of range'; END IF;
89
+
90
+ tmp := rv - 1;
91
+ WHILE tmp > 0 LOOP bb := bb + 1; tmp := div(tmp, 256); END LOOP;
92
+ d := 4 * ((bb + 3) / 4) + 4;
93
+ p := '\x010201'::bytea || gfc64_num_to_bytes(radix, 3) || '\x0a'::bytea
94
+ || gfc64_num_to_bytes(u % 256, 1) || gfc64_num_to_bytes(n, 4) || gfc64_num_to_bytes(t, 4);
95
+ pad := decode(repeat('00', (((-t - bb - 1) % 16) + 16) % 16), 'hex');
96
+
97
+ FOR k IN 0..9 LOOP
98
+ i := CASE WHEN decrypting THEN 9 - k ELSE k END;
99
+ q := tweak || pad || gfc64_num_to_bytes(i, 1)
100
+ || gfc64_num_to_bytes(CASE WHEN decrypting THEN a ELSE b END, bb);
101
+ -- R = PRF(P || Q): CBC-MAC with a zero IV.
102
+ r := decode(repeat('00', 16), 'hex');
103
+ j := 0;
104
+ WHILE j < length(p || q) LOOP
105
+ r := gfc64_aes(key, gfc64_xor16(r, substring(p || q FROM j + 1 FOR 16)));
106
+ j := j + 16;
107
+ END LOOP;
108
+ s := r;
109
+ j := 1;
110
+ WHILE length(s) < d LOOP
111
+ s := s || gfc64_aes(key, gfc64_xor16(r, gfc64_num_to_bytes(j, 16)));
112
+ j := j + 1;
113
+ END LOOP;
114
+ y := gfc64_bytes_to_num(substring(s FROM 1 FOR d));
115
+ m := CASE WHEN i % 2 = 0 THEN u ELSE v END;
116
+ rm := power(radix::numeric, m);
117
+ IF decrypting THEN
118
+ c := mod(mod(b - y, rm) + rm, rm);
119
+ b := a;
120
+ a := c;
121
+ ELSE
122
+ c := mod(a + y, rm);
123
+ a := b;
124
+ b := c;
125
+ END IF;
126
+ END LOOP;
127
+ RETURN a * rv + b;
128
+ END $$;
129
+
130
+ -- ---- Crockford base32 -------------------------------------------------------
131
+
132
+ CREATE OR REPLACE FUNCTION gfc64_crockford_encode(x numeric, len int, grp int DEFAULT 0) RETURNS text
133
+ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE AS $$
134
+ DECLARE
135
+ alphabet text := '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
136
+ out text := '';
137
+ BEGIN
138
+ FOR i IN 1..len LOOP
139
+ out := substr(alphabet, mod(x, 32)::int + 1, 1) || out;
140
+ x := div(x, 32);
141
+ END LOOP;
142
+ IF x > 0 THEN RAISE EXCEPTION 'value too large for % characters', len; END IF;
143
+ IF grp > 0 THEN
144
+ out := array_to_string(ARRAY(SELECT substr(out, g, grp) FROM generate_series(1, len, grp) AS g), '-');
145
+ END IF;
146
+ RETURN out;
147
+ END $$;
148
+
149
+ -- Forgiving: any case, O as 0, I/L as 1, spaces and hyphens ignored.
150
+ -- NULL when it isn't a code of exactly len characters.
151
+ CREATE OR REPLACE FUNCTION gfc64_crockford_decode(s text, len int) RETURNS numeric
152
+ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE AS $$
153
+ DECLARE
154
+ alphabet text := '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
155
+ t text := translate(upper(s), 'OIL -', '011');
156
+ n numeric := 0;
157
+ pos int;
158
+ BEGIN
159
+ IF length(t) <> len THEN RETURN NULL; END IF;
160
+ FOR i IN 1..len LOOP
161
+ pos := strpos(alphabet, substr(t, i, 1));
162
+ IF pos = 0 THEN RETURN NULL; END IF;
163
+ n := n * 32 + (pos - 1);
164
+ END LOOP;
165
+ RETURN n;
166
+ END $$;
167
+
168
+ -- ---- key + trigger ------------------------------------------------------------
169
+
170
+ -- Keys live in a table that only the owner (the migration role) can read.
171
+ CREATE TABLE IF NOT EXISTS gfc64_keys (name text PRIMARY KEY, key bytea NOT NULL CHECK (length(key) IN (16, 24, 32)));
172
+ REVOKE ALL ON gfc64_keys FROM PUBLIC;
173
+
174
+ -- BEFORE INSERT: column defaults (the id's nextval) are already applied, so
175
+ -- NEW.<pk> is the row's real id. Fills <column> when it's NULL.
176
+ -- Arguments: column, key name, tweak, prefix, code length, group size, pk column.
177
+ -- SECURITY DEFINER so it can read gfc64_keys though the app's role can't.
178
+ CREATE OR REPLACE FUNCTION gfc64_assign_code() RETURNS trigger
179
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
180
+ DECLARE
181
+ col text := TG_ARGV[0];
182
+ key_name text := TG_ARGV[1];
183
+ tweak text := TG_ARGV[2];
184
+ prefix text := coalesce(TG_ARGV[3], '');
185
+ len int := coalesce(TG_ARGV[4], '8')::int;
186
+ grp int := coalesce(TG_ARGV[5], '4')::int;
187
+ pk text := coalesce(TG_ARGV[6], 'id');
188
+ row_json jsonb := to_jsonb(NEW);
189
+ k bytea;
190
+ BEGIN
191
+ IF row_json ->> col IS NOT NULL THEN RETURN NEW; END IF;
192
+ SELECT key INTO STRICT k FROM gfc64_keys WHERE name = key_name;
193
+ NEW := jsonb_populate_record(NEW, jsonb_build_object(col,
194
+ prefix || gfc64_crockford_encode(
195
+ gfc64_ff1(k, convert_to(tweak, 'UTF8'), 32, len, (row_json ->> pk)::numeric), len, grp)));
196
+ RETURN NEW;
197
+ END $$;
198
+ REVOKE ALL ON FUNCTION gfc64_assign_code() FROM PUBLIC;
199
+
200
+ -- Example:
201
+ -- INSERT INTO gfc64_keys VALUES ('default', decode('<64 hex chars>', 'hex'));
202
+ -- CREATE TRIGGER invoices_number BEFORE INSERT ON invoices FOR EACH ROW
203
+ -- EXECUTE FUNCTION gfc64_assign_code('number', 'default', 'invoices.number', 'APP-', '8', '4');
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gfc64
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abe Voelker
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-18 00:00:00.000000000 Z
11
+ date: 2026-11-19 00:00:00.000000000 Z
12
12
  dependencies: []
13
13
  description: 'Hides sequential primary key counts without resorting to UUIDs or GUIDs:
14
14
  a Feistel cipher over 16-64 bit integers, NIST SP 800-38G FF1, and short-code formatters
@@ -27,6 +27,7 @@ files:
27
27
  - lib/gfc64/format.rb
28
28
  - lib/gfc64/keys.rb
29
29
  - lib/gfc64/model.rb
30
+ - sql/gfc64_postgres.sql
30
31
  homepage: https://github.com/abevoelker/gfc64
31
32
  licenses:
32
33
  - MIT