gfc64 0.1.0 → 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.
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
@@ -0,0 +1,176 @@
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
+ # alphabet: the characters, lowest value first
20
+ # bits: the width of the numbers (match GFC64's bits:), or
21
+ # length: a fixed number of characters (match FF1's length:
22
+ # when FF1's radix is this alphabet's size)
23
+ # case_sensitive: false folds input to the alphabet's case
24
+ # aliases: extra input characters read as another, e.g. "O" => "0"
25
+ # group: on output, put `separator` every `group` characters
26
+ # ignore: input characters dropped before decoding (spaces and
27
+ # hyphens by default; the separator always is)
28
+ def initialize(alphabet, bits: nil, length: nil, case_sensitive: true, aliases: {}, group: nil, separator: "-", ignore: " -")
29
+ chars = alphabet.chars
30
+ raise ArgumentError, "alphabet needs at least 2 distinct characters" if chars.uniq.size != chars.size || chars.size < 2
31
+ raise ArgumentError, "give exactly one of bits: or length:" unless bits.nil? ^ length.nil?
32
+ raise ArgumentError, "bits must be a positive Integer" unless bits.nil? || (bits.is_a?(Integer) && bits.positive?)
33
+ 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?)
35
+
36
+ @alphabet = alphabet.dup.freeze
37
+ @chars = chars.freeze
38
+ @base = chars.size
39
+ if bits
40
+ @bits = bits
41
+ @max = (1 << bits) - 1
42
+ @length = 1
43
+ @length += 1 while @base**@length <= @max
44
+ else
45
+ @length = length
46
+ @max = @base**length - 1
47
+ @bits = @max.bit_length
48
+ end
49
+ @case_sensitive = case_sensitive
50
+ @group = group
51
+ @separator = separator
52
+ dropped = (ignore.to_s + separator.to_s).chars.uniq - chars
53
+ @ignore = dropped.empty? ? nil : /[#{Regexp.escape(dropped.join)}]/
54
+ @values = {}
55
+ chars.each_with_index { |c, i| @values[fold(c)] = i }
56
+ aliases.each do |from, to|
57
+ raise ArgumentError, "alias target #{to.inspect} isn't in the alphabet" unless @values.key?(fold(to))
58
+
59
+ @values[fold(from)] = @values[fold(to)]
60
+ end
61
+ end
62
+
63
+ def encode(number)
64
+ unless number.is_a?(Integer) && number.between?(0, @max)
65
+ raise ArgumentError, "Number must be from 0 to #{@max}"
66
+ end
67
+
68
+ out = Array.new(@length, @chars[0])
69
+ i = @length - 1
70
+ while number.positive?
71
+ number, digit = number.divmod(@base)
72
+ out[i] = @chars[digit]
73
+ i -= 1
74
+ end
75
+ s = out.join
76
+ group ? s.scan(/.{1,#{group}}/).join(separator) : s
77
+ end
78
+
79
+ # strict: true accepts only the exact canonical form (what encode
80
+ # returns: its case, its separators, no look-alikes or extra spaces),
81
+ # e.g. for input from machines. The default forgives what the alphabet
82
+ # safely can, for input from people.
83
+ def decode(string, strict: false)
84
+ number = lenient_decode(string)
85
+ if strict && (canonical = encode(number)) != string
86
+ raise ArgumentError, "#{string[0, 64].inspect} isn't in canonical form (#{canonical.inspect})"
87
+ end
88
+
89
+ number
90
+ end
91
+
92
+ # The canonical form of a code however it was typed, or nil when it
93
+ # isn't one: normalize("tcnh r99b") => "TCNH-R99B" (with group: 4).
94
+ def normalize(string)
95
+ encode(lenient_decode(string))
96
+ rescue ArgumentError
97
+ nil
98
+ end
99
+
100
+ # True when the string is exactly the canonical form.
101
+ def canonical?(string)
102
+ !string.nil? && normalize(string) == string
103
+ end
104
+
105
+ private def lenient_decode(string)
106
+ raise ArgumentError, "expected a String" unless string.is_a?(String)
107
+
108
+ s = @ignore ? string.gsub(@ignore, "") : string
109
+ raise ArgumentError, "expected #{@length} characters, got #{s.length}" unless s.length == @length
110
+
111
+ number = s.each_char.reduce(0) do |acc, c|
112
+ digit = @values[fold(c)]
113
+ raise ArgumentError, "#{c.inspect} isn't a valid character" if digit.nil?
114
+
115
+ acc * @base + digit
116
+ end
117
+ raise ArgumentError, "#{string.inspect} is out of range (above #{@max})" if number > @max
118
+
119
+ number
120
+ end
121
+
122
+ # The largest value a code can hold.
123
+ attr_reader :max
124
+
125
+ # The alphabet's size: pass it as FF1's radix:.
126
+ def radix
127
+ @base
128
+ end
129
+
130
+ # True when the string decodes (right length, characters and range).
131
+ def valid?(string, strict: false)
132
+ decode(string, strict: strict)
133
+ true
134
+ rescue ArgumentError
135
+ false
136
+ end
137
+
138
+ private
139
+
140
+ def fold(c)
141
+ @case_sensitive ? c : c.upcase
142
+ end
143
+ end
144
+
145
+ # Douglas Crockford's base32 (https://www.crockford.com/base32.html):
146
+ # digits and capitals without I, L, O, U. Input is forgiving: any case,
147
+ # O reads as 0, I and L as 1, hyphens and spaces ignored. 40 bits is
148
+ # exactly 8 characters.
149
+ class Crockford32 < Alphabet
150
+ ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
151
+
152
+ def initialize(bits: nil, length: nil, group: nil, separator: "-")
153
+ super(ALPHABET, bits: bits, length: length, case_sensitive: false, aliases: { "O" => "0", "I" => "1", "L" => "1" },
154
+ group: group, separator: separator)
155
+ end
156
+ end
157
+
158
+ # Bitcoin's base58: digits and both cases without 0, O, I, l. Shorter than
159
+ # base32 (40 bits is 7 characters) but case-sensitive, so better for links
160
+ # and QR codes than for reading aloud.
161
+ class Base58 < Alphabet
162
+ ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
163
+
164
+ def initialize(bits: nil, length: nil, group: nil, separator: "-")
165
+ super(ALPHABET, bits: bits, length: length, group: group, separator: separator)
166
+ end
167
+ end
168
+
169
+ # Plain digits, zero-padded (40 bits is 13 digits), e.g. for phone keypads.
170
+ class Decimal < Alphabet
171
+ def initialize(bits: nil, length: nil, group: nil, separator: "-")
172
+ super("0123456789", bits: bits, length: length, group: group, separator: separator)
173
+ end
174
+ end
175
+ end
176
+ 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