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/active_record.rb
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
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.
|
|
4
6
|
module ActiveRecord
|
|
5
7
|
def self.[](gfc)
|
|
6
8
|
Module.new do
|
|
@@ -21,8 +23,13 @@ class GFC64
|
|
|
21
23
|
@gfc ||= f_gfc.respond_to?(:call) ? f_gfc.call : f_gfc
|
|
22
24
|
end
|
|
23
25
|
|
|
26
|
+
# Accepts the String from params; a bad or out-of-range value raises
|
|
27
|
+
# ActiveRecord::RecordNotFound (404) instead of ArgumentError (500).
|
|
24
28
|
def find_gfc(gfc_id)
|
|
25
|
-
|
|
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}"
|
|
26
33
|
end
|
|
27
34
|
end
|
|
28
35
|
|
data/lib/gfc64/config.rb
ADDED
|
@@ -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
|
data/lib/gfc64/ff1.rb
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
|
|
6
|
+
class GFC64
|
|
7
|
+
# FF1 format-preserving encryption, NIST SP 800-38G (Algorithms 7 and 8):
|
|
8
|
+
# encrypts a string of `length` digits in base `radix` into another string
|
|
9
|
+
# of the same length and base, with AES (128, 192 or 256-bit key) and an
|
|
10
|
+
# optional tweak. Checked against NIST's published FF1 sample vectors.
|
|
11
|
+
#
|
|
12
|
+
# ff1 = GFC64::FF1.new(key_bytes, radix: 32, length: 8, tweak: "invoices")
|
|
13
|
+
# code = ff1.encrypt(42) # => an Integer below 32**8
|
|
14
|
+
# ff1.decrypt(code) # => 42
|
|
15
|
+
#
|
|
16
|
+
# Pair it with GFC64::Format (e.g. Crockford32.new(length: 8)) for codes.
|
|
17
|
+
class FF1
|
|
18
|
+
ROUNDS = 10
|
|
19
|
+
# SP 800-38G Rev. 1 requires radix**minlen >= 1,000,000.
|
|
20
|
+
MIN_DOMAIN = 1_000_000
|
|
21
|
+
MAX_RADIX = 65_536
|
|
22
|
+
|
|
23
|
+
attr_reader :radix, :length, :tweak
|
|
24
|
+
|
|
25
|
+
# key: the AES key as raw bytes (16, 24 or 32 bytes), secret and random:
|
|
26
|
+
# FF1.generate_key makes one; from hex, [hex].pack("H*"). Example
|
|
27
|
+
# keys are refused unless insecure_test_key: true (tests only).
|
|
28
|
+
# radix: the base of each digit, 2 to 65,536
|
|
29
|
+
# length: digits per value when using encrypt/decrypt on Integers
|
|
30
|
+
# (encrypt_digits takes any length the domain rule allows)
|
|
31
|
+
# tweak: public bytes that select an independent permutation (default "")
|
|
32
|
+
def initialize(key, radix:, length: nil, tweak: "", insecure_test_key: false)
|
|
33
|
+
raise ArgumentError, "key must be a String of bytes" unless key.is_a?(String)
|
|
34
|
+
|
|
35
|
+
key = key.b
|
|
36
|
+
raise ArgumentError, "key must be 16, 24 or 32 bytes (AES-128/192/256)" unless [16, 24, 32].include?(key.bytesize)
|
|
37
|
+
|
|
38
|
+
Keys.check!(key, insecure_test_key)
|
|
39
|
+
raise ArgumentError, "radix must be an Integer from 2 to #{MAX_RADIX}" unless radix.is_a?(Integer) && radix.between?(2, MAX_RADIX)
|
|
40
|
+
|
|
41
|
+
@radix = radix
|
|
42
|
+
@tweak = check_tweak(tweak)
|
|
43
|
+
@length = length
|
|
44
|
+
check_length!(length) unless length.nil?
|
|
45
|
+
@cipher_name = "AES-#{key.bytesize * 8}-ECB"
|
|
46
|
+
@key = key
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# A random AES-256 key: raw bytes, or hex (64 characters) for storing in
|
|
50
|
+
# an env var or secrets manager; load hex with [hex].pack("H*").
|
|
51
|
+
def self.generate_key(hex: false)
|
|
52
|
+
key = SecureRandom.bytes(32)
|
|
53
|
+
hex ? key.unpack1("H*") : key
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Integer in, Integer out: 0 <= number < radix**length.
|
|
57
|
+
def encrypt(number, tweak: nil)
|
|
58
|
+
from_digits(encrypt_digits(to_digits(number), tweak: tweak))
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def decrypt(number, tweak: nil)
|
|
62
|
+
from_digits(decrypt_digits(to_digits(number), tweak: tweak))
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Digit arrays (each 0...radix, most significant first), as in the standard.
|
|
66
|
+
def encrypt_digits(x, tweak: nil)
|
|
67
|
+
feistel(x, tweak.nil? ? @tweak : check_tweak(tweak), :encrypt)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def decrypt_digits(x, tweak: nil)
|
|
71
|
+
feistel(x, tweak.nil? ? @tweak : check_tweak(tweak), :decrypt)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# The number of values (radix**length).
|
|
75
|
+
def domain_size
|
|
76
|
+
raise ArgumentError, "no length: given" if length.nil?
|
|
77
|
+
|
|
78
|
+
radix**length
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
private
|
|
82
|
+
|
|
83
|
+
def feistel(x, t, direction)
|
|
84
|
+
check_digits!(x)
|
|
85
|
+
n = x.size
|
|
86
|
+
u = n / 2
|
|
87
|
+
v = n - u
|
|
88
|
+
a = x[0, u]
|
|
89
|
+
b = x[u, v]
|
|
90
|
+
bb = byte_len(v) # b in the standard
|
|
91
|
+
d = 4 * ((bb + 3) / 4) + 4
|
|
92
|
+
p_block = [1, 2, 1].pack("C3") + int_bytes(radix, 3) + [10, u % 256].pack("C2") + [n, t.bytesize].pack("N2")
|
|
93
|
+
pad = "\0".b * ((-t.bytesize - bb - 1) % 16)
|
|
94
|
+
aes = new_aes
|
|
95
|
+
|
|
96
|
+
if direction == :encrypt
|
|
97
|
+
ROUNDS.times do |i|
|
|
98
|
+
y = round_value(aes, p_block, t, pad, i, num(b), bb, d)
|
|
99
|
+
m = i.even? ? u : v
|
|
100
|
+
c = (num(a) + y) % radix**m
|
|
101
|
+
a, b = b, str(c, m)
|
|
102
|
+
end
|
|
103
|
+
else
|
|
104
|
+
(ROUNDS - 1).downto(0) do |i|
|
|
105
|
+
y = round_value(aes, p_block, t, pad, i, num(a), bb, d)
|
|
106
|
+
m = i.even? ? u : v
|
|
107
|
+
c = (num(b) - y) % radix**m
|
|
108
|
+
b, a = a, str(c, m)
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
a + b
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Steps 6.i-6.iv: Q, R = PRF(P || Q), S, y.
|
|
115
|
+
def round_value(aes, p_block, t, pad, i, half_num, bb, d)
|
|
116
|
+
q = t + pad + [i].pack("C") + int_bytes(half_num, bb)
|
|
117
|
+
r = prf(aes, p_block + q)
|
|
118
|
+
s = r.dup
|
|
119
|
+
j = 1
|
|
120
|
+
while s.bytesize < d
|
|
121
|
+
s << ciph(aes, xor16(r, int_bytes(j, 16)))
|
|
122
|
+
j += 1
|
|
123
|
+
end
|
|
124
|
+
s[0, d].unpack1("H*").to_i(16)
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# CBC-MAC with a zero IV (the standard's PRF).
|
|
128
|
+
def prf(aes, data)
|
|
129
|
+
y = "\0".b * 16
|
|
130
|
+
(0...data.bytesize).step(16) { |o| y = ciph(aes, xor16(y, data[o, 16])) }
|
|
131
|
+
y
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def ciph(aes, block)
|
|
135
|
+
aes.update(block)
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def new_aes
|
|
139
|
+
aes = OpenSSL::Cipher.new(@cipher_name).encrypt
|
|
140
|
+
aes.key = @key
|
|
141
|
+
aes.padding = 0
|
|
142
|
+
aes
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def xor16(a, b)
|
|
146
|
+
a.bytes.zip(b.bytes).map { |x, y| x ^ y }.pack("C*")
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# b = ceil(ceil(v * log2(radix)) / 8), without floating point:
|
|
150
|
+
# ceil(log2(N)) is the bit length of N - 1.
|
|
151
|
+
def byte_len(v)
|
|
152
|
+
((radix**v - 1).bit_length + 7) / 8
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def int_bytes(x, len)
|
|
156
|
+
return "".b if len.zero?
|
|
157
|
+
|
|
158
|
+
[x.to_s(16).rjust(len * 2, "0")].pack("H*")
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
def num(digits)
|
|
162
|
+
digits.reduce(0) { |acc, dgt| acc * radix + dgt }
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
def str(x, m)
|
|
166
|
+
out = Array.new(m, 0)
|
|
167
|
+
(m - 1).downto(0) { |i| x, out[i] = x.divmod(radix) }
|
|
168
|
+
out
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def to_digits(number)
|
|
172
|
+
raise ArgumentError, "no length: given; use encrypt_digits" if length.nil?
|
|
173
|
+
unless number.is_a?(Integer) && number.between?(0, radix**length - 1)
|
|
174
|
+
raise ArgumentError, "Number must be from 0 to #{radix**length - 1} (#{length} base-#{radix} digits)"
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
str(number, length)
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def from_digits(digits)
|
|
181
|
+
num(digits)
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def check_tweak(tweak)
|
|
185
|
+
raise ArgumentError, "tweak must be a String" unless tweak.is_a?(String)
|
|
186
|
+
|
|
187
|
+
tweak.b.freeze
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def check_length!(len)
|
|
191
|
+
raise ArgumentError, "length must be an Integer of at least 2" unless len.is_a?(Integer) && len >= 2
|
|
192
|
+
raise ArgumentError, "radix**length must be at least #{MIN_DOMAIN} (SP 800-38G)" if radix**len < MIN_DOMAIN
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def check_digits!(x)
|
|
196
|
+
raise ArgumentError, "expected an Array of digits" unless x.is_a?(Array)
|
|
197
|
+
|
|
198
|
+
check_length!(x.size)
|
|
199
|
+
return if x.all? { |dgt| dgt.is_a?(Integer) && dgt.between?(0, radix - 1) }
|
|
200
|
+
|
|
201
|
+
raise ArgumentError, "every digit must be an Integer from 0 to #{radix - 1}"
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
end
|
data/lib/gfc64/format.rb
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class GFC64
|
|
4
|
+
# Turn encrypted numbers into short strings people can read and type, and
|
|
5
|
+
# back. Every formatter is fixed-length for its width, so codes line up and a
|
|
6
|
+
# missing or extra character is caught instead of silently decoding to some
|
|
7
|
+
# other number.
|
|
8
|
+
#
|
|
9
|
+
# gfc = GFC64.new(key, bits: 40)
|
|
10
|
+
# fmt = GFC64::Format::Crockford32.new(bits: 40, group: 4)
|
|
11
|
+
# code = fmt.encode(gfc.encrypt(42)) # => "7KQM-R3XH"
|
|
12
|
+
# gfc.decrypt(fmt.decode("7kqm r3xh")) # => 42
|
|
13
|
+
module Format
|
|
14
|
+
# Any alphabet: the length is the fewest characters that can hold every
|
|
15
|
+
# value of `bits` bits.
|
|
16
|
+
class Alphabet
|
|
17
|
+
attr_reader :alphabet, :bits, :length, :group, :separator
|
|
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
|
+
|
|
29
|
+
# alphabet: the characters, lowest value first
|
|
30
|
+
# bits: the width of the numbers (match GFC64's bits:), or
|
|
31
|
+
# length: a fixed number of characters (match FF1's length:
|
|
32
|
+
# when FF1's radix is this alphabet's size)
|
|
33
|
+
# case_sensitive: false folds input to the alphabet's case
|
|
34
|
+
# aliases: extra input characters read as another, e.g. "O" => "0"
|
|
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.
|
|
42
|
+
# ignore: input characters dropped before decoding (spaces and
|
|
43
|
+
# hyphens by default; the separator always is)
|
|
44
|
+
def initialize(alphabet, bits: nil, length: nil, case_sensitive: true, aliases: {}, group: nil, separator: "-", ignore: " -",
|
|
45
|
+
check: false)
|
|
46
|
+
chars = alphabet.chars
|
|
47
|
+
raise ArgumentError, "alphabet needs at least 2 distinct characters" if chars.uniq.size != chars.size || chars.size < 2
|
|
48
|
+
raise ArgumentError, "give exactly one of bits: or length:" unless bits.nil? ^ length.nil?
|
|
49
|
+
raise ArgumentError, "bits must be a positive Integer" unless bits.nil? || (bits.is_a?(Integer) && bits.positive?)
|
|
50
|
+
raise ArgumentError, "length must be a positive Integer" unless length.nil? || (length.is_a?(Integer) && length.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
|
|
58
|
+
|
|
59
|
+
@alphabet = alphabet.dup.freeze
|
|
60
|
+
@chars = chars.freeze
|
|
61
|
+
@base = chars.size
|
|
62
|
+
if bits
|
|
63
|
+
@bits = bits
|
|
64
|
+
@max = (1 << bits) - 1
|
|
65
|
+
@length = 1
|
|
66
|
+
@length += 1 while @base**@length <= @max
|
|
67
|
+
else
|
|
68
|
+
@length = length
|
|
69
|
+
@max = @base**length - 1
|
|
70
|
+
@bits = @max.bit_length
|
|
71
|
+
end
|
|
72
|
+
@case_sensitive = case_sensitive
|
|
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
|
|
80
|
+
@separator = separator
|
|
81
|
+
dropped = (ignore.to_s + separator.to_s).chars.uniq - chars
|
|
82
|
+
@ignore = dropped.empty? ? nil : /[#{Regexp.escape(dropped.join)}]/
|
|
83
|
+
@values = {}
|
|
84
|
+
chars.each_with_index { |c, i| @values[fold(c)] = i }
|
|
85
|
+
aliases.each do |from, to|
|
|
86
|
+
raise ArgumentError, "alias target #{to.inspect} isn't in the alphabet" unless @values.key?(fold(to))
|
|
87
|
+
|
|
88
|
+
@values[fold(from)] = @values[fold(to)]
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def encode(number)
|
|
93
|
+
unless number.is_a?(Integer) && number.between?(0, @max)
|
|
94
|
+
raise ArgumentError, "Number must be from 0 to #{@max}"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
out = Array.new(@length, @chars[0])
|
|
98
|
+
i = @length - 1
|
|
99
|
+
while number.positive?
|
|
100
|
+
number, digit = number.divmod(@base)
|
|
101
|
+
out[i] = @chars[digit]
|
|
102
|
+
i -= 1
|
|
103
|
+
end
|
|
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)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# strict: true accepts only the exact canonical form (what encode
|
|
119
|
+
# returns: its case, its separators, no look-alikes or extra spaces),
|
|
120
|
+
# e.g. for input from machines. The default forgives what the alphabet
|
|
121
|
+
# safely can, for input from people.
|
|
122
|
+
def decode(string, strict: false)
|
|
123
|
+
number = lenient_decode(string)
|
|
124
|
+
if strict && (canonical = encode(number)) != string
|
|
125
|
+
raise ArgumentError, "#{string[0, 64].inspect} isn't in canonical form (#{canonical.inspect})"
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
number
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# The canonical form of a code however it was typed, or nil when it
|
|
132
|
+
# isn't one: normalize("tcnh r99b") => "TCNH-R99B" (with group: 4).
|
|
133
|
+
def normalize(string)
|
|
134
|
+
encode(lenient_decode(string))
|
|
135
|
+
rescue ArgumentError
|
|
136
|
+
nil
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# True when the string is exactly the canonical form.
|
|
140
|
+
def canonical?(string)
|
|
141
|
+
!string.nil? && normalize(string) == string
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
private def lenient_decode(string)
|
|
145
|
+
raise ArgumentError, "expected a String" unless string.is_a?(String)
|
|
146
|
+
|
|
147
|
+
s = @ignore ? string.gsub(@ignore, "") : string
|
|
148
|
+
raise ArgumentError, "expected #{code_length} characters, got #{s.length}" unless s.length == code_length
|
|
149
|
+
|
|
150
|
+
digits = s.each_char.map do |c|
|
|
151
|
+
digit = @values[fold(c)]
|
|
152
|
+
raise ArgumentError, "#{c.inspect} isn't a valid character" if digit.nil?
|
|
153
|
+
|
|
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
|
|
160
|
+
end
|
|
161
|
+
number = digits.reduce(0) { |acc, d| acc * @base + d }
|
|
162
|
+
raise ArgumentError, "#{string.inspect} is out of range (above #{@max})" if number > @max
|
|
163
|
+
|
|
164
|
+
number
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# The largest value a code can hold.
|
|
168
|
+
attr_reader :max
|
|
169
|
+
|
|
170
|
+
# The alphabet's size: pass it as FF1's radix:.
|
|
171
|
+
def radix
|
|
172
|
+
@base
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# True when the string decodes (right length, characters and range).
|
|
176
|
+
def valid?(string, strict: false)
|
|
177
|
+
decode(string, strict: strict)
|
|
178
|
+
true
|
|
179
|
+
rescue ArgumentError
|
|
180
|
+
false
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
private
|
|
184
|
+
|
|
185
|
+
def fold(c)
|
|
186
|
+
@case_sensitive ? c : c.upcase
|
|
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
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
# Douglas Crockford's base32 (https://www.crockford.com/base32.html):
|
|
224
|
+
# digits and capitals without I, L, O, U. Input is forgiving: any case,
|
|
225
|
+
# O reads as 0, I and L as 1, hyphens and spaces ignored. 40 bits is
|
|
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).
|
|
230
|
+
class Crockford32 < Alphabet
|
|
231
|
+
ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
|
|
232
|
+
|
|
233
|
+
def initialize(bits: nil, length: nil, group: nil, separator: "-", check: false)
|
|
234
|
+
super(ALPHABET, bits: bits, length: length, case_sensitive: false, aliases: { "O" => "0", "I" => "1", "L" => "1" },
|
|
235
|
+
group: group, separator: separator, check: check)
|
|
236
|
+
end
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# Bitcoin's base58: digits and both cases without 0, O, I, l. Shorter than
|
|
240
|
+
# base32 (40 bits is 7 characters) but case-sensitive, so better for links
|
|
241
|
+
# and QR codes than for reading aloud.
|
|
242
|
+
class Base58 < Alphabet
|
|
243
|
+
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
|
|
244
|
+
|
|
245
|
+
def initialize(bits: nil, length: nil, group: nil, separator: "-")
|
|
246
|
+
super(ALPHABET, bits: bits, length: length, group: group, separator: separator)
|
|
247
|
+
end
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
# Plain digits, zero-padded (40 bits is 13 digits), e.g. for phone keypads.
|
|
251
|
+
class Decimal < Alphabet
|
|
252
|
+
def initialize(bits: nil, length: nil, group: nil, separator: "-")
|
|
253
|
+
super("0123456789", bits: bits, length: length, group: group, separator: separator)
|
|
254
|
+
end
|
|
255
|
+
end
|
|
256
|
+
end
|
|
257
|
+
end
|
data/lib/gfc64/keys.rb
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "securerandom"
|
|
4
|
+
|
|
5
|
+
class GFC64
|
|
6
|
+
# The key is what makes encrypted values unpredictable: two apps with the
|
|
7
|
+
# same tweak but their own random keys get unrelated sequences. A key copied
|
|
8
|
+
# from documentation or test vectors makes every value computable by anyone,
|
|
9
|
+
# so those are refused unless a test says otherwise.
|
|
10
|
+
module Keys
|
|
11
|
+
README_KEY = "ffb5e3600fc27924f97dc055440403b10ce97160261f2a87eee576584cf942e5"
|
|
12
|
+
NIST_FF1_KEYS = %w[
|
|
13
|
+
2B7E151628AED2A6ABF7158809CF4F3C
|
|
14
|
+
2B7E151628AED2A6ABF7158809CF4F3CEF4359D8D580AA4F
|
|
15
|
+
2B7E151628AED2A6ABF7158809CF4F3CEF4359D8D580AA4F7F036D6F04FC6A94
|
|
16
|
+
].freeze
|
|
17
|
+
KNOWN_HEX = ([README_KEY] + NIST_FF1_KEYS).map(&:downcase).freeze
|
|
18
|
+
KNOWN_RAW = KNOWN_HEX.map { |h| [h].pack("H*") }.freeze
|
|
19
|
+
|
|
20
|
+
module_function
|
|
21
|
+
|
|
22
|
+
def check!(key, insecure_test_key)
|
|
23
|
+
return if insecure_test_key
|
|
24
|
+
|
|
25
|
+
raw = key.b
|
|
26
|
+
reason =
|
|
27
|
+
if KNOWN_HEX.include?(raw.downcase) || KNOWN_RAW.include?(raw)
|
|
28
|
+
"is a published example key (README or NIST test vectors)"
|
|
29
|
+
elsif raw.bytes.uniq.size <= 2
|
|
30
|
+
"isn't random (it repeats one or two bytes)"
|
|
31
|
+
end
|
|
32
|
+
return unless reason
|
|
33
|
+
|
|
34
|
+
raise ArgumentError, "This key #{reason}, so anyone could compute every value. " \
|
|
35
|
+
"Generate one with GFC64.generate_key or GFC64::FF1.generate_key and keep it secret; " \
|
|
36
|
+
"in tests, pass insecure_test_key: true."
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# A random key for GFC64.new, as 64 hex characters (fine in an env var).
|
|
41
|
+
def self.generate_key
|
|
42
|
+
SecureRandom.hex(32)
|
|
43
|
+
end
|
|
44
|
+
end
|