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 +4 -4
- data/CHANGELOG.md +60 -0
- data/README.md +485 -46
- data/lib/gfc64/active_record.rb +8 -1
- data/lib/gfc64/config.rb +54 -0
- data/lib/gfc64/ff1.rb +204 -0
- data/lib/gfc64/format.rb +257 -0
- data/lib/gfc64/keys.rb +44 -0
- data/lib/gfc64/model.rb +403 -0
- data/lib/gfc64.rb +81 -25
- data/sql/gfc64_postgres.sql +203 -0
- metadata +16 -7
data/lib/gfc64/model.rb
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class GFC64
|
|
4
|
+
# Raised by a guarded find (has_public_id guard_find: true) given a String
|
|
5
|
+
# that isn't an id. An ArgumentError, so it's a loud error, not a 404.
|
|
6
|
+
class UnsafeFind < ArgumentError; end
|
|
7
|
+
|
|
8
|
+
# ActiveRecord helpers. In Rails every model has them; elsewhere,
|
|
9
|
+
# `include GFC64::Model`.
|
|
10
|
+
#
|
|
11
|
+
# class Customer < ApplicationRecord
|
|
12
|
+
# has_public_id bits: 40, format: GFC64::Format::Base58.new(bits: 40)
|
|
13
|
+
# end
|
|
14
|
+
# customer_path(customer) # => "/customers/BQZbwjf"
|
|
15
|
+
# Customer.find_by_public_id!(params[:id]) # bad or unknown => RecordNotFound
|
|
16
|
+
#
|
|
17
|
+
# class Invoice < ApplicationRecord
|
|
18
|
+
# has_code :number, prefix: "APP-", # made from the id, stored in "number"
|
|
19
|
+
# format: GFC64::Format::Crockford32.new(length: 8, group: 4)
|
|
20
|
+
# end
|
|
21
|
+
# Invoice.create!.number # => "APP-TCNH-R99B"
|
|
22
|
+
# Invoice.find_by_code!(:number, "app tcnh-r99b") # any case, spacing, O/I/L
|
|
23
|
+
module Model
|
|
24
|
+
def self.included(base)
|
|
25
|
+
base.extend(ClassMethods)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
# Raised by the bang finders; ActiveRecord::RecordNotFound when available,
|
|
29
|
+
# so Rails answers 404.
|
|
30
|
+
def self.not_found_error
|
|
31
|
+
defined?(::ActiveRecord::RecordNotFound) ? ::ActiveRecord::RecordNotFound : KeyError
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
module ClassMethods
|
|
35
|
+
# The primary key, encrypted for URLs; nothing is stored.
|
|
36
|
+
#
|
|
37
|
+
# bits: width of the cipher (IDs must stay below 2**bits); 64 by default
|
|
38
|
+
# format: a GFC64::Format to show it (default: the plain number)
|
|
39
|
+
# cipher: :feistel (default) or :ff1 (needs a length:-based format;
|
|
40
|
+
# its radix and length set the domain)
|
|
41
|
+
# tweak: defaults to the table name, so each model gets its own mapping;
|
|
42
|
+
# false for none (the same numbers as the 0.1.0 mixin)
|
|
43
|
+
# prefix: added in front, e.g. "INV-"; optional, any case, when decoding
|
|
44
|
+
# param: false keeps to_param as the plain id
|
|
45
|
+
# guard_find: true makes find raise GFC64::UnsafeFind when given a
|
|
46
|
+
# String that isn't all digits, instead of ActiveRecord reading
|
|
47
|
+
# its leading digits ("7KQM-R3XH" as 7) and returning another
|
|
48
|
+
# record. Covers Model.find, relations and associations.
|
|
49
|
+
def has_public_id(bits: 64, format: nil, cipher: :feistel, tweak: nil, prefix: "", param: true, guard_find: false)
|
|
50
|
+
opts = { bits: bits, format: format, cipher: cipher, tweak: tweak, prefix: prefix.to_s }
|
|
51
|
+
GFC64::Model.check_options!(opts, :has_public_id)
|
|
52
|
+
@gfc64_public_id = opts
|
|
53
|
+
include PublicIdMethods
|
|
54
|
+
define_method(:to_param) { public_id } if param
|
|
55
|
+
GFC64::Model.guard_find!(self) if guard_find
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
# A code stored in `column`, made on create from the record's own
|
|
59
|
+
# primary key (by default) or a separate counter: encrypted (FF1 by
|
|
60
|
+
# default), formatted, prefixed.
|
|
61
|
+
#
|
|
62
|
+
# sequence: :primary_key (default) reuses the auto-incremented id. On
|
|
63
|
+
# Postgres the id is taken from the table's own sequence
|
|
64
|
+
# before the INSERT, so the code goes in the same write and
|
|
65
|
+
# the column can be NOT NULL; elsewhere the code is filled in
|
|
66
|
+
# right after the INSERT (same transaction; the column must
|
|
67
|
+
# allow NULL). Or a sequence name / callable for numbering
|
|
68
|
+
# that's independent of the id.
|
|
69
|
+
# format: a GFC64::Format (required)
|
|
70
|
+
# prefix: added in front, e.g. "APP-"; optional when looking up
|
|
71
|
+
# cipher: :ff1 (default; any alphabet) or :feistel (power-of-two
|
|
72
|
+
# alphabets only)
|
|
73
|
+
# tweak: defaults to "table.column"
|
|
74
|
+
def has_code(column, format:, sequence: :primary_key, prefix: "", cipher: :ff1, tweak: nil)
|
|
75
|
+
column = column.to_sym
|
|
76
|
+
opts = { sequence: sequence, format: format, prefix: prefix.to_s, cipher: cipher, tweak: tweak }
|
|
77
|
+
GFC64::Model.check_options!(opts, :has_code)
|
|
78
|
+
gfc64_codes[column] = opts
|
|
79
|
+
include CodeMethods
|
|
80
|
+
return unless respond_to?(:before_create)
|
|
81
|
+
|
|
82
|
+
before_create { gfc64_before_create_code(column) }
|
|
83
|
+
after_create { gfc64_after_create_code(column) }
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def gfc64_codes
|
|
87
|
+
@gfc64_codes ||= {}
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# ---- public ids ------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
def encode_public_id(id)
|
|
93
|
+
o = public_id_options
|
|
94
|
+
n = public_id_cipher.encrypt(id)
|
|
95
|
+
o[:prefix] + (o[:format] ? o[:format].encode(n) : n.to_s)
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# The record id for a public id String (prefix optional; any case and
|
|
99
|
+
# spacing the format allows), or nil when it isn't one.
|
|
100
|
+
#
|
|
101
|
+
# strict: true accepts only the exact canonical form (what to_param
|
|
102
|
+
# returns), e.g. for input from machines.
|
|
103
|
+
def decode_public_id(value, strict: false)
|
|
104
|
+
if strict
|
|
105
|
+
id = decode_public_id(value)
|
|
106
|
+
return id && encode_public_id(id) == value ? id : nil
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
o = public_id_options
|
|
110
|
+
GFC64::Model.prefix_candidates(value, o[:prefix]).each do |s|
|
|
111
|
+
begin
|
|
112
|
+
n = o[:format] ? o[:format].decode(s) : Integer(s, 10)
|
|
113
|
+
return public_id_cipher.decrypt(n)
|
|
114
|
+
rescue ArgumentError, TypeError
|
|
115
|
+
next
|
|
116
|
+
end
|
|
117
|
+
end
|
|
118
|
+
nil
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def find_by_public_id(value, strict: false)
|
|
122
|
+
id = decode_public_id(value, strict: strict)
|
|
123
|
+
id && find_by(primary_key => id)
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def find_by_public_id!(value, strict: false)
|
|
127
|
+
find_by_public_id(value, strict: strict) || raise(GFC64::Model.not_found_error, "Couldn't find #{name} with public id #{value.to_s[0, 64].inspect}")
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# The canonical form of a public id however it was typed (for a redirect
|
|
131
|
+
# to the canonical URL), or nil when it isn't one.
|
|
132
|
+
def canonical_public_id(value)
|
|
133
|
+
id = decode_public_id(value)
|
|
134
|
+
id && encode_public_id(id)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def public_id_cipher
|
|
138
|
+
gfc64_cached(:public_id) { GFC64::Model.build_cipher(public_id_options, default_tweak: table_name.to_s) }
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# ---- stored codes ----------------------------------------------------
|
|
142
|
+
|
|
143
|
+
# The stored form of a code, however it was typed; nil when it isn't one.
|
|
144
|
+
def normalize_code(column, value)
|
|
145
|
+
o = code_options(column)
|
|
146
|
+
GFC64::Model.prefix_candidates(value, o[:prefix]).each do |c|
|
|
147
|
+
begin
|
|
148
|
+
return o[:prefix] + o[:format].encode(o[:format].decode(c))
|
|
149
|
+
rescue ArgumentError
|
|
150
|
+
next
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
nil
|
|
154
|
+
rescue ArgumentError, TypeError
|
|
155
|
+
nil
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# strict: true accepts only the stored canonical form.
|
|
159
|
+
def find_by_code(column, value, strict: false)
|
|
160
|
+
code = normalize_code(column, value)
|
|
161
|
+
return nil if code.nil? || (strict && code != value)
|
|
162
|
+
|
|
163
|
+
find_by(column.to_sym => code)
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
def find_by_code!(column, value, strict: false)
|
|
167
|
+
find_by_code(column, value, strict: strict) || raise(GFC64::Model.not_found_error, "Couldn't find #{name} with #{column} #{value.to_s[0, 64].inspect}")
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# The sequence value a code was made from (for bookkeeping), or nil.
|
|
171
|
+
def code_sequence_value(column, code)
|
|
172
|
+
o = code_options(column)
|
|
173
|
+
stored = normalize_code(column, code) or return nil
|
|
174
|
+
code_cipher(column).decrypt(o[:format].decode(stored[o[:prefix].length..-1]))
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
# The code for a counter value; with no value, the next one from the
|
|
178
|
+
# configured sequence (not for sequence: :primary_key, which uses the
|
|
179
|
+
# record's id).
|
|
180
|
+
def generate_code(column, value = nil)
|
|
181
|
+
o = code_options(column)
|
|
182
|
+
if value.nil?
|
|
183
|
+
raise ArgumentError, "#{column} uses the primary key; pass the id" if o[:sequence] == :primary_key
|
|
184
|
+
|
|
185
|
+
value = o[:sequence].respond_to?(:call) ? o[:sequence].call : next_sequence_value(o[:sequence])
|
|
186
|
+
end
|
|
187
|
+
o[:prefix] + o[:format].encode(code_cipher(column).encrypt(Integer(value)))
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
# The next id from the table's own sequence (Postgres), or nil where
|
|
191
|
+
# that isn't available.
|
|
192
|
+
def gfc64_prefetch_primary_key
|
|
193
|
+
seq = gfc64_primary_key_sequence
|
|
194
|
+
seq && connection.select_value("SELECT nextval(#{connection.quote(seq)})")
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
# The table's id sequence, looked up once per model (it doesn't change);
|
|
198
|
+
# nil off Postgres or when the id has no sequence.
|
|
199
|
+
def gfc64_primary_key_sequence
|
|
200
|
+
return @gfc64_pk_sequence if defined?(@gfc64_pk_sequence)
|
|
201
|
+
|
|
202
|
+
conn = connection
|
|
203
|
+
@gfc64_pk_sequence =
|
|
204
|
+
if conn.adapter_name.to_s =~ /postg/i
|
|
205
|
+
conn.select_value("SELECT pg_get_serial_sequence(#{conn.quote(table_name.to_s)}, #{conn.quote(primary_key.to_s)})")
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
def code_cipher(column)
|
|
210
|
+
gfc64_cached(:"code_#{column}") do
|
|
211
|
+
GFC64::Model.build_cipher(code_options(column), default_tweak: "#{table_name}.#{column}")
|
|
212
|
+
end
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
private
|
|
216
|
+
|
|
217
|
+
def public_id_options
|
|
218
|
+
klass = self
|
|
219
|
+
while klass.respond_to?(:public_id_cipher)
|
|
220
|
+
o = klass.instance_variable_get(:@gfc64_public_id)
|
|
221
|
+
return o if o
|
|
222
|
+
|
|
223
|
+
klass = klass.superclass
|
|
224
|
+
end
|
|
225
|
+
raise ArgumentError, "#{name} has no has_public_id"
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
def code_options(column)
|
|
229
|
+
klass = self
|
|
230
|
+
while klass.respond_to?(:gfc64_codes)
|
|
231
|
+
o = klass.gfc64_codes[column.to_sym]
|
|
232
|
+
return o if o
|
|
233
|
+
|
|
234
|
+
klass = klass.superclass
|
|
235
|
+
end
|
|
236
|
+
raise ArgumentError, "#{name} has no has_code #{column.inspect}"
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
def next_sequence_value(name)
|
|
240
|
+
conn = connection
|
|
241
|
+
conn.select_value("SELECT nextval(#{conn.quote(name.to_s)})")
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
def gfc64_cached(slot)
|
|
245
|
+
gen = GFC64.cipher_generation
|
|
246
|
+
@gfc64_ciphers = {} if @gfc64_cipher_gen != gen
|
|
247
|
+
@gfc64_cipher_gen = gen
|
|
248
|
+
@gfc64_ciphers[slot] ||= yield
|
|
249
|
+
end
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
module PublicIdMethods
|
|
253
|
+
def public_id
|
|
254
|
+
id = self[self.class.primary_key]
|
|
255
|
+
id && self.class.encode_public_id(id)
|
|
256
|
+
end
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
module CodeMethods
|
|
260
|
+
def assign_code(column)
|
|
261
|
+
self[column] = self.class.generate_code(column)
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
def code_sequence_value(column)
|
|
265
|
+
self.class.code_sequence_value(column, self[column])
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
private
|
|
269
|
+
|
|
270
|
+
def gfc64_blank?(column)
|
|
271
|
+
self[column].nil? || self[column].to_s.empty?
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
def gfc64_before_create_code(column)
|
|
275
|
+
return unless gfc64_blank?(column)
|
|
276
|
+
|
|
277
|
+
if self.class.send(:code_options, column)[:sequence] != :primary_key
|
|
278
|
+
assign_code(column)
|
|
279
|
+
return
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
pk = self.class.primary_key
|
|
283
|
+
self[pk] ||= self.class.gfc64_prefetch_primary_key
|
|
284
|
+
self[column] = self.class.generate_code(column, self[pk]) if self[pk]
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
# Databases without a sequence to read ahead: the id exists now.
|
|
288
|
+
def gfc64_after_create_code(column)
|
|
289
|
+
return unless gfc64_blank?(column)
|
|
290
|
+
|
|
291
|
+
update_columns(column => self.class.generate_code(column, self[self.class.primary_key]))
|
|
292
|
+
end
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
# ---- guarded find ---------------------------------------------------------
|
|
296
|
+
|
|
297
|
+
# Prepended to the model's class and its relation classes.
|
|
298
|
+
module FindGuard
|
|
299
|
+
def find(*args, &block)
|
|
300
|
+
GFC64::Model.check_find_args!(self, args) unless block # with a block it's Enumerable#find
|
|
301
|
+
super
|
|
302
|
+
end
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
def self.guard_find!(model)
|
|
306
|
+
model.singleton_class.prepend(FindGuard)
|
|
307
|
+
return unless defined?(::ActiveRecord::Relation) && model.respond_to?(:relation_delegate_class)
|
|
308
|
+
|
|
309
|
+
relation_classes = [::ActiveRecord::Relation]
|
|
310
|
+
relation_classes << ::ActiveRecord::AssociationRelation if defined?(::ActiveRecord::AssociationRelation)
|
|
311
|
+
relation_classes << ::ActiveRecord::Associations::CollectionProxy if defined?(::ActiveRecord::Associations::CollectionProxy)
|
|
312
|
+
relation_classes.each { |k| model.relation_delegate_class(k).prepend(FindGuard) }
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
def self.check_find_args!(scope, args)
|
|
316
|
+
args.flatten.each do |a|
|
|
317
|
+
next unless a.is_a?(String)
|
|
318
|
+
next if a.match?(/\A\d+\z/)
|
|
319
|
+
|
|
320
|
+
model = scope.respond_to?(:model) ? scope.model : scope
|
|
321
|
+
raise UnsafeFind, "#{model.name}.find was given #{a[0, 64].inspect}, which isn't an id: ActiveRecord would read " \
|
|
322
|
+
"its leading digits and could return another record. For a public id use " \
|
|
323
|
+
"#{model.name}.find_by_public_id!(...)."
|
|
324
|
+
end
|
|
325
|
+
end
|
|
326
|
+
|
|
327
|
+
# ---- shared ---------------------------------------------------------------
|
|
328
|
+
|
|
329
|
+
# What to try decoding. The prefix is optional and matched in any case;
|
|
330
|
+
# only the prefix itself is removed, so the format alone decides which
|
|
331
|
+
# remaining characters (spaces, separators, look-alikes) it can safely
|
|
332
|
+
# ignore. Tried in order: without the full prefix ("INV-"), without its
|
|
333
|
+
# letters alone ("inv tcnh"), then as given (a code may start with the
|
|
334
|
+
# prefix's letters). Codes have a fixed length, so at most one fits.
|
|
335
|
+
def self.prefix_candidates(value, prefix)
|
|
336
|
+
s = value.to_s.strip
|
|
337
|
+
p = prefix.to_s
|
|
338
|
+
return [s] if p.empty?
|
|
339
|
+
|
|
340
|
+
out = []
|
|
341
|
+
out << s[p.length..-1] if s.length >= p.length && s[0, p.length].casecmp(p).zero?
|
|
342
|
+
core = p.gsub(/[^[:alnum:]]/, "")
|
|
343
|
+
out << s[core.length..-1] if !core.empty? && core != p && s.length >= core.length && s[0, core.length].casecmp(core).zero?
|
|
344
|
+
out << s
|
|
345
|
+
out.uniq
|
|
346
|
+
end
|
|
347
|
+
|
|
348
|
+
def self.check_options!(o, macro)
|
|
349
|
+
unless %i[feistel ff1].include?(o[:cipher])
|
|
350
|
+
raise ArgumentError, "#{macro}: cipher must be :feistel or :ff1"
|
|
351
|
+
end
|
|
352
|
+
fmt = o[:format]
|
|
353
|
+
if macro == :has_code
|
|
354
|
+
raise ArgumentError, "has_code: format: is required (e.g. GFC64::Format::Crockford32.new(length: 8))" unless fmt.is_a?(GFC64::Format::Alphabet)
|
|
355
|
+
unless o[:sequence].respond_to?(:call) || o[:sequence].is_a?(String) || o[:sequence].is_a?(Symbol)
|
|
356
|
+
raise ArgumentError, "has_code: sequence: must be :primary_key, a sequence name or a callable"
|
|
357
|
+
end
|
|
358
|
+
end
|
|
359
|
+
if fmt && !fmt.is_a?(GFC64::Format::Alphabet)
|
|
360
|
+
raise ArgumentError, "#{macro}: format must be a GFC64::Format"
|
|
361
|
+
end
|
|
362
|
+
if o[:cipher] == :ff1 && fmt.nil?
|
|
363
|
+
raise ArgumentError, "#{macro}: cipher: :ff1 needs a format: (its radix and length set the domain)"
|
|
364
|
+
end
|
|
365
|
+
if o[:cipher] == :feistel && fmt
|
|
366
|
+
bits = o[:bits] || fmt.bits
|
|
367
|
+
if (2**bits - 1) > fmt.max
|
|
368
|
+
raise ArgumentError, "#{macro}: #{bits}-bit values don't fit #{fmt.length} characters of this format"
|
|
369
|
+
end
|
|
370
|
+
end
|
|
371
|
+
o[:tweak] = o[:tweak].to_s unless o[:tweak].nil? || o[:tweak] == false
|
|
372
|
+
end
|
|
373
|
+
|
|
374
|
+
def self.build_cipher(o, default_tweak:)
|
|
375
|
+
key = GFC64.config.key
|
|
376
|
+
# false: no tweak at all (the 0.1.0 mixin's numbers).
|
|
377
|
+
tweak = o[:tweak] == false ? nil : (o[:tweak] || default_tweak)
|
|
378
|
+
test_key = GFC64.config.insecure_test_key ? true : false
|
|
379
|
+
if o[:cipher] == :ff1
|
|
380
|
+
fmt = o[:format]
|
|
381
|
+
GFC64::FF1.new([key].pack("H*"), radix: fmt.radix, length: fmt.length, tweak: tweak || "", insecure_test_key: test_key)
|
|
382
|
+
else
|
|
383
|
+
bits = o[:bits] || feistel_bits(o[:format])
|
|
384
|
+
GFC64.new(key, bits: bits, tweak: tweak, insecure_test_key: test_key)
|
|
385
|
+
end
|
|
386
|
+
end
|
|
387
|
+
|
|
388
|
+
# For has_code with cipher: :feistel: the format's width, which must be a
|
|
389
|
+
# power-of-two alphabet filled exactly (e.g. Crockford32 length 8 = 40 bits).
|
|
390
|
+
def self.feistel_bits(fmt)
|
|
391
|
+
bits = fmt.bits
|
|
392
|
+
unless fmt.max == 2**bits - 1 && bits.even? && bits.between?(GFC64::MIN_BITS, GFC64::MAX_BITS)
|
|
393
|
+
raise ArgumentError, "cipher: :feistel needs a power-of-two alphabet filling an even 16-64 bits; use cipher: :ff1"
|
|
394
|
+
end
|
|
395
|
+
|
|
396
|
+
bits
|
|
397
|
+
end
|
|
398
|
+
end
|
|
399
|
+
end
|
|
400
|
+
|
|
401
|
+
if defined?(ActiveSupport) && ActiveSupport.respond_to?(:on_load)
|
|
402
|
+
ActiveSupport.on_load(:active_record) { include GFC64::Model }
|
|
403
|
+
end
|
data/lib/gfc64.rb
CHANGED
|
@@ -3,57 +3,113 @@
|
|
|
3
3
|
require "openssl"
|
|
4
4
|
require "securerandom"
|
|
5
5
|
|
|
6
|
+
# A balanced Feistel cipher over the integers 0...2**bits: every value maps to
|
|
7
|
+
# exactly one other value of the same width, and back again with the same key.
|
|
6
8
|
class GFC64
|
|
7
|
-
VERSION = "
|
|
9
|
+
VERSION = "1.1.0".freeze
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
MIN_BITS = 16
|
|
12
|
+
MAX_BITS = 64
|
|
13
|
+
# Narrower blocks have smaller halves, so they get more rounds by default
|
|
14
|
+
# (NIST's FF1 format-preserving cipher uses 10). 64-bit keeps 3 so existing
|
|
15
|
+
# encrypted values don't change.
|
|
16
|
+
DEFAULT_ROUNDS = 3
|
|
17
|
+
DEFAULT_NARROW_ROUNDS = 10
|
|
18
|
+
|
|
19
|
+
attr_reader :rounds, :key, :block_size, :bits, :tweak
|
|
20
|
+
|
|
21
|
+
# bits: the width of the numbers encrypted, an even number from 16 to 64.
|
|
22
|
+
# Every number from 0 to 2**bits - 1 encrypts to a different number in the
|
|
23
|
+
# same range. The default (64) gives exactly the same results as 0.1.0.
|
|
24
|
+
#
|
|
25
|
+
# tweak: an optional public String that selects one of many independent
|
|
26
|
+
# ciphers under the same key (e.g. "invoices" vs "orders"). It isn't a
|
|
27
|
+
# secret and isn't per record: values are only collision-free within one
|
|
28
|
+
# key + tweak. No tweak gives the same results as before tweaks existed.
|
|
29
|
+
#
|
|
30
|
+
# key: a secret, random String; GFC64.generate_key makes one. Example keys
|
|
31
|
+
# from the README are refused unless insecure_test_key: true (tests only).
|
|
32
|
+
def initialize(key, rounds: nil, bits: MAX_BITS, tweak: nil, insecure_test_key: false)
|
|
33
|
+
unless bits.is_a?(Integer) && bits.even? && bits.between?(MIN_BITS, MAX_BITS)
|
|
34
|
+
raise ArgumentError, "bits must be an even Integer from #{MIN_BITS} to #{MAX_BITS}"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
raise ArgumentError, "key must be a String" unless key.is_a?(String)
|
|
38
|
+
raise ArgumentError, "tweak must be a String or nil" unless tweak.nil? || tweak.is_a?(String)
|
|
39
|
+
|
|
40
|
+
Keys.check!(key, insecure_test_key)
|
|
10
41
|
|
|
11
|
-
def initialize(key, rounds: 3)
|
|
12
42
|
@key = key
|
|
13
|
-
@
|
|
14
|
-
@
|
|
43
|
+
@tweak = tweak&.b&.freeze
|
|
44
|
+
@bits = bits
|
|
45
|
+
@half_bits = bits / 2
|
|
46
|
+
@half_mask = (1 << @half_bits) - 1
|
|
47
|
+
@max = (1 << bits) - 1
|
|
48
|
+
@block_size = bits % 8 == 0 ? bits / 8 : Rational(bits, 8) # in bytes
|
|
49
|
+
@rounds = rounds || (bits == MAX_BITS ? DEFAULT_ROUNDS : DEFAULT_NARROW_ROUNDS)
|
|
50
|
+
raise ArgumentError, "rounds must be a positive Integer" unless @rounds.is_a?(Integer) && @rounds.positive?
|
|
51
|
+
|
|
52
|
+
@round_keys = Array.new(@rounds) { |round| derive_round_key(key, round) }
|
|
15
53
|
end
|
|
16
54
|
|
|
17
55
|
def encrypt(number)
|
|
18
|
-
|
|
56
|
+
check!(number)
|
|
19
57
|
|
|
20
|
-
|
|
21
|
-
left, right = number >> 32, number & 0xFFFFFFFF
|
|
58
|
+
left, right = number >> @half_bits, number & @half_mask
|
|
22
59
|
|
|
23
60
|
rounds.times do |round|
|
|
24
|
-
|
|
25
|
-
aes = OpenSSL::Cipher.new('AES-128-ECB').encrypt
|
|
26
|
-
aes.key = round_key
|
|
27
|
-
f = aes.update([right].pack('N')) + aes.final
|
|
28
|
-
left, right = right, left ^ f.unpack1('N')
|
|
61
|
+
left, right = right, left ^ f(@round_keys[round], right)
|
|
29
62
|
end
|
|
30
63
|
|
|
31
|
-
|
|
32
|
-
(left << 32) | right
|
|
64
|
+
(left << @half_bits) | right
|
|
33
65
|
end
|
|
34
66
|
|
|
35
67
|
def decrypt(number)
|
|
36
|
-
|
|
68
|
+
check!(number)
|
|
37
69
|
|
|
38
|
-
left, right = number >>
|
|
70
|
+
left, right = number >> @half_bits, number & @half_mask
|
|
39
71
|
|
|
40
72
|
rounds.times do |round|
|
|
41
|
-
|
|
42
|
-
aes = OpenSSL::Cipher.new('AES-128-ECB').encrypt
|
|
43
|
-
aes.key = round_key
|
|
44
|
-
f = aes.update([left].pack('N')) + aes.final
|
|
45
|
-
left, right = right ^ f.unpack1('N'), left
|
|
73
|
+
left, right = right ^ f(@round_keys[rounds - round - 1], left), left
|
|
46
74
|
end
|
|
47
75
|
|
|
48
|
-
(left <<
|
|
76
|
+
(left << @half_bits) | right
|
|
49
77
|
end
|
|
50
78
|
|
|
51
79
|
private
|
|
52
80
|
|
|
81
|
+
def check!(number)
|
|
82
|
+
return if number.is_a?(Integer) && number.between?(0, @max)
|
|
83
|
+
|
|
84
|
+
raise ArgumentError, "Number must be a #{bits}-bit integer (0 to #{@max})"
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Round function: AES-128 of the half block, truncated to the half's width.
|
|
88
|
+
def f(round_key, half)
|
|
89
|
+
aes = OpenSSL::Cipher.new("AES-128-ECB").encrypt
|
|
90
|
+
aes.key = round_key
|
|
91
|
+
(aes.update([half].pack("N")) + aes.final).unpack1("N") & @half_mask
|
|
92
|
+
end
|
|
93
|
+
|
|
53
94
|
def derive_round_key(key, round)
|
|
54
|
-
|
|
55
|
-
|
|
95
|
+
if tweak
|
|
96
|
+
# Length-prefixed, so ("ab", "c") and ("a", "bc") can't collide.
|
|
97
|
+
material = "#{key}\0gfc64\0bits=#{bits}\0tweak=".b + [tweak.bytesize].pack("N") + tweak + [round].pack("N")
|
|
98
|
+
OpenSSL::Digest::SHA256.digest(material)[0...16]
|
|
99
|
+
elsif bits == MAX_BITS
|
|
100
|
+
# Unchanged from 0.1.0 so 64-bit values stay the same.
|
|
101
|
+
OpenSSL::Digest::SHA256.digest(key + [round].pack("L"))[0...16]
|
|
102
|
+
else
|
|
103
|
+
# The width is part of the round key, so the same key at different
|
|
104
|
+
# widths gives unrelated ciphers; "N" (big-endian) is portable.
|
|
105
|
+
OpenSSL::Digest::SHA256.digest("#{key}\0gfc64\0bits=#{bits}\0" + [round].pack("N"))[0...16]
|
|
106
|
+
end
|
|
56
107
|
end
|
|
57
108
|
end
|
|
58
109
|
|
|
110
|
+
require "gfc64/keys"
|
|
111
|
+
require "gfc64/config"
|
|
59
112
|
require "gfc64/active_record"
|
|
113
|
+
require "gfc64/format"
|
|
114
|
+
require "gfc64/ff1"
|
|
115
|
+
require "gfc64/model"
|