epithet 1.1.0 → 2.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: 100d3ac2b640a77419d9d6f45228ed67251285ed6f0bf390b9249573d20db887
4
- data.tar.gz: 5350064afb6799feec528888c475bcc0d8e403272f13332d00bdcd43b7bcd47c
3
+ metadata.gz: 40b8e5a401923aeaaf82f8340d43747433ea1440f7de4b1628087c326a916622
4
+ data.tar.gz: bf139e16eecab4aa544981b15f28fb267f1e55e38ca37a0828c6836c064319c3
5
5
  SHA512:
6
- metadata.gz: 77e5c3acde924854471a36ede3d43e010fcf4f2bd7f4a49b75c753e7c80e4c0651355c0c33ec28a9d1c229abf14fd5da61b40c1eae2a23cbd31f8c8ef94cd9a5
7
- data.tar.gz: 21a8c95376177e30642bed7aefd1b1f87ccd5f0a00d489592c154ed1ecf86cdf076df57f04f98d01ad802b4ea1c62367b5afcc0fdd165501f95fe081ac10efd9
6
+ metadata.gz: 324dec4e145ca1d5e8f3b9a22c3788ab3e9d1771d614c7dab5c94288888c59ce7235cbdd1a2dcd878015321f2264ae21702020b8bc9f8b6aaf3191bc50df9adc
7
+ data.tar.gz: 55f0b6b5bd0061c3545f9c644bfaec6eb3e7721d0df33b1217a52384da63b4ff96c0d5848f2d0340460bf3e3b8c6e9aef38cd9e677665e6abcfa09f1fd4a9024
data/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.0.0 - 2026-07-16
4
+
5
+ ### Breaking changes
6
+
7
+ - The subkey-derivation option `context:` replaces `salt:`, to avoid confusion with scrypt's salt parameter.
8
+ - Subkey derivation now binds the configured cipher and digest names (lowercased) into the HKDF info.
9
+ - Nil and empty-string prefixes now yield bare params with no separator.
10
+ - Config no longer exposes the alphabet string, it carries the Block58 codec around instead.
11
+ - Drop support for Rubies < 3.4.
12
+
13
+ ### Other changes
14
+
15
+ - Raise Epithet::FormatError (< ArgumentError) on invalid wire format
16
+ - Improve handling of string encodings
17
+ - Additional invariants
18
+ - Friendlier errors
19
+ - Documentation improvements
20
+
3
21
  ## 1.1.0 - 2026-07-14
4
22
 
5
23
  - Freeze config strings upon object initialization
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Epithet
2
2
 
3
- Epithet generates stable, compact, purposefully prefixed Base58 identifiers from 64-bit integers for reversible obfuscation and tamper detection.
3
+ Epithet generates stable, compact, purposefully prefixed base58 identifiers from 64-bit integers for reversible obfuscation and tamper detection.
4
4
 
5
5
  * https://github.com/inopinatus/epithet
6
6
  * https://inopinatus.github.io/epithet/
@@ -21,7 +21,7 @@ gem install epithet
21
21
 
22
22
  ## Usage
23
23
 
24
- With `EPITHET_PASSPHRASE="example only"`:
24
+ With `EPITHET_PASSPHRASE=example_only`:
25
25
 
26
26
  ```ruby
27
27
  require 'epithet'
@@ -29,7 +29,8 @@ require 'epithet'
29
29
  def epithet_initialize
30
30
  Epithet.configure(
31
31
  passphrase: ENV.fetch('EPITHET_PASSPHRASE'),
32
- salt: 'v1'
32
+ scrypt: { salt: 'myapp/production' },
33
+ context: 'v1'
33
34
  )
34
35
  end
35
36
 
@@ -38,17 +39,17 @@ user_epithet = Epithet.new('user')
38
39
 
39
40
  id = 42
40
41
  param = user_epithet.encode(id)
41
- # => "user_VsuNnfEYQJJTJYE3n28jaY"
42
+ # => "user_GikJf7Y58t5sgqJpifjgZy"
42
43
 
43
44
  user_epithet.decode(param)
44
45
  # => 42
45
46
  ```
46
47
 
47
- Configuration at initialisation is recommended, because deriving key material from the passphrase uses scrypt, and is consequently expensive. The `salt:` is optional; it's included when deriving the subkey material for obfuscating and tamper resistance, and may be useful for additional context discrimination or during secrets rotation.
48
+ Configuration once at initialisation is recommended, because deriving key material from the passphrase uses scrypt, and is consequently expensive. The `context:` is optional; this parameter is included when deriving the subkey material for obfuscating and tamper resistance, and support purpose separation such as key rotation. The scrypt step is seasoned by a salt, which defaults to a fixed constant; set an application-specific salt, as in the example above, so that two applications inadvertently sharing a passphrase never derive the same keys.
48
49
 
49
50
  Refer to the Epithet rdoc for the full set of configuration options.
50
51
 
51
- Note that `decode` returns `nil` when authentication fails and raises ArgumentError on invalid formats.
52
+ Note that `decode` returns `nil` when authentication fails, and raises `Epithet::FormatError` (an ArgumentError) on invalid formats.
52
53
 
53
54
  ## Development
54
55
 
data/SECURITY.md CHANGED
@@ -2,10 +2,10 @@
2
2
 
3
3
  ## Cryptographic considerations
4
4
 
5
- The primary construction is `AES-256-ECB(id(8B) + HMAC-SHA256(id)[0,7])` with the result base58
6
- encoded for transmission and a contextual prefix prepended. Subkeys for AES and HMAC are by default
5
+ The primary construction is `AES-256-ECB(id(8B) + MSB_64(HMAC-SHA256(id)))` with the result base58
6
+ encoded for transmission and a contextual prefix prepended. Subkeys for AES and HMAC are by default
7
7
  derived with HKDF using an internal key generator that takes IKM from a passphrase via scrypt,
8
- salting generated keys by prefix and purpose.
8
+ salting generated keys by prefix and context and binding them by algorithm.
9
9
 
10
10
  This library is intended for high-performance obfuscation of integer sequences, deflection of casual
11
11
  tampering, and conversion to a compact, stable wire parameter format that is hard to guess and hard
@@ -13,38 +13,58 @@ to predict. Although it uses standard cryptographic primitives to do so, the de
13
13
  the compact format means it is not intended to defeat nation-state security services, talented
14
14
  cryptographers, or even a well-resourced enterprise.
15
15
 
16
- The identifiers produced are intentionally deterministic i.e. replayable and reusable. For privacy,
17
- confidentiality, and authentication purposes they should therefore be considered equivalent to the
18
- plaintext integer they represent, and those concerns must still be addressed in the usual manner.
19
-
20
- The tamper detection is necessarily probabilistic, because the MAC is truncated.
21
-
22
- Encodings are canonical, producing exactly one string per id, and Epithet will reject attempts to
23
- decode a value exceeding the 128-bit block.
16
+ An epithet should never be used as an authentication token, only as an object identifier. The
17
+ 64-bit tag is shorter than the minimum RFC 2104 §5 recommends for message authentication, and the
18
+ tamper detection is necessarily probabilistic because the MAC is truncated. After N independent
19
+ forgery attempts, expected success is approximately (N/2^{64}). The identifiers produced are
20
+ intentionally deterministic i.e. replayable and reusable. For privacy, confidentiality, and
21
+ authentication purposes they should be considered equivalent to the plaintext integer they
22
+ represent, and those concerns must still be addressed in the usual manner.
24
23
 
25
24
  If configuring alternative cipher algorithms, note that only 128-bit block ciphers that function
26
- without IV/nonce requirements are accepted. Streaming ciphers (e.g. chacha20) or block ciphers in
25
+ without IV/nonce requirements are accepted. Streaming ciphers (e.g. chacha20) or block ciphers in
27
26
  streaming modes (e.g. aes-256-ctr) must not be used; no nonce/IV value is included in construction,
28
27
  making them trivially vulnerable to known-plaintext attacks. These, CBC/OCB, and other IV/nonce
29
28
  modes may also be rejected by Epithet's guardrails.
30
29
 
31
- If configuring alternative digest algorithms, note that any algorithm may be accepted whenever they
32
- it produces at least 64 bits of output. HMAC does not rest on collision resistance, so even dated
33
- digests are not trivially forgeable here, but algorithms other than the defaults step outside the
34
- supported security profile. If you must stray, stay within the SHA-2 family.
30
+ If configuring alternative digest algorithms, note that any algorithm may be accepted that produces
31
+ at least 64 bits of output. HMAC does not rest on collision resistance, so even dated digests are
32
+ not trivially forgeable here, but algorithms other than the defaults step outside the supported
33
+ profile. If you must stray, we recommend staying within the SHA-2 family.
34
+
35
+ Encodings are canonical, producing exactly one string per id, and Epithet will reject attempts to
36
+ decode a value exceeding the 128-bit block.
35
37
 
36
38
  A weak, guessable, or disclosed passphrase will compromise the obfuscation and tamper-detection
37
39
  properties.
38
40
 
39
41
  Use Epithet at your own risk.
40
42
 
41
- ## On salt
43
+ ## On seasoning
44
+
45
+ Epithet uses salt in two ways. Firstly, if the default key generator is in use, as part of the
46
+ setup-time scrypt operation turning the configured passphrase into initial keying material.
47
+ Secondly, for the HKDF extract phase to separate derived subkeys by some application-specific
48
+ division such as purpose or rotation epoch.
49
+
50
+ To avoid confusing the two uses, the HKDF salt is not referred to directly in Epithet's public API,
51
+ and is instead derived from the context and prefix parameters that are documented instead.
52
+
53
+ Epithet does not store or verify passwords; the scrypt salt, and the context & prefix parameters
54
+ used in the HKDF salt, are non-secret configuration and may be safely committed to source control.
55
+
56
+ ## On rotation
57
+
58
+ This gem provides a deterministic primitive; managing lifecycle, policy, and application-aware
59
+ responses to legacy identifiers is intentionally left to framework/application-specific adapters.
60
+ When implementing an adapter, the context parameter is recommended as the basis for key rotation.
61
+
62
+ ## Startup cost
42
63
 
43
- Epithet uses salt in two ways. Firstly, as part of a scrypt operation to turn the configured
44
- passphrase into initial keying material. Secondly, to supply an additional affordance to separate
45
- derived subkeys by some application-specific division such as purpose or rotation epoch. Epithet
46
- does not store or verify passwords; both uses of salt are non-secret configuration and may safely be
47
- committed to source control.
64
+ Turning a passphrase into initial keying material is intrinsically expensive. The default scrypt
65
+ parameters (N=2^17, r=8) cost roughly 128 MiB of peak memory and a fraction of a second of CPU.
66
+ When deployed as indicated this is a boot-time cost, incurred once per configuration rather than
67
+ per encode/decode, but budget for it in memory-constrained deployments.
48
68
 
49
69
  ## Vulnerabilities
50
70
 
data/examples/basic.rb CHANGED
@@ -2,10 +2,13 @@
2
2
 
3
3
  require 'epithet'
4
4
 
5
+ # Using a random passphrase means that epithet identifiers are effectively
6
+ # ephemeral, since decoding is limited to the lifetime of this process.
5
7
  def epithet_initialize
6
8
  Epithet.configure(
7
- passphrase: ENV.fetch('EPITHET_PASSPHRASE') { 'example only' },
8
- salt: 'v1'
9
+ passphrase: ENV.fetch('EPITHET_PASSPHRASE') { Random.bytes(32) },
10
+ scrypt: { salt: 'myapp/production' },
11
+ context: 'v1'
9
12
  )
10
13
  end
11
14
 
@@ -13,6 +16,6 @@ epithet_initialize
13
16
  user_epithet = Epithet.new('user')
14
17
 
15
18
  id = Integer(ARGV.shift || 42)
16
- param = user_epithet.encode(id) #=> "user_VsuNnfEYQJJTJYE3n28jaY"
19
+ param = user_epithet.encode(id) #=> "user_KYM3B4d5ce1NNsv52rAoPg"
17
20
 
18
21
  puts "User(#{user_epithet.decode(param)}) => #{param}"
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Epithet
4
- # `= '1.1.0'`
5
- VERSION = '1.1.0'
4
+ # `= '2.0.0'`
5
+ VERSION = '2.0.0'
6
6
  end
data/lib/epithet.rb CHANGED
@@ -10,56 +10,63 @@ require 'openssl'
10
10
  # prefix (typically a model or table name), produces a replayable string parameter of
11
11
  # consistent length, with modest obfuscation and authentication properties.
12
12
  #
13
- # Pseudo-AEAD is via `AES-256-ECB(id(8B) + HMAC-SHA256(id)[0,7])` with the result
13
+ # Pseudo-AEAD is via `AES-256-ECB(id(8B) + MSB_64(HMAC-SHA256(id)))` with the result
14
14
  # base58 encoded for transmission and the contextual prefix prepended.
15
15
  #
16
- # Encodings are canonical; a given configuration accepts exactly one string per id.
16
+ # Encodings are canonical; a given configuration produces exactly one string per id.
17
17
  #
18
18
  # Subkeys for AES and HMAC are by default derived with HKDF using an internal key
19
19
  # generator that takes IKM from a passphrase via scrypt. An alternative key generator
20
- # may be injected via Config objects. Subkeys are salted by prefix and an optional
21
- # additional salt, which may be useful for purpose separation or rotation.
20
+ # may be injected via Config objects. Subkeys are salted by prefix and an optional
21
+ # context string, which may be useful for purpose separation or rotation, and each
22
+ # subkey is bound to the configured name of the algorithm that consumes it.
22
23
  #
23
24
  # Example usage:
24
25
  #
25
26
  # # in setup-environment.sh
26
- # EPITHET_PASSPHRASE='example only'
27
+ # EPITHET_PASSPHRASE='example_only' ; export EPITHET_PASSPHRASE
27
28
  #
28
29
  # # ... later, in Ruby ...
29
30
  # Epithet.configure(passphrase: ENV.fetch('EPITHET_PASSPHRASE'))
30
31
  # user_epithet = Epithet.new('user')
31
- # user_epithet.encode(1) #=> "user_DAG6Joc5JmgygTBuEo8a9K"
32
+ # user_epithet.encode(1) #=> "user_NEwRoiarS9wdmiLmjEtti3"
32
33
  #
33
34
  class Epithet
35
+ # Raised by #decode when the input is not valid wire format.
36
+ FormatError = Class.new(ArgumentError)
37
+
34
38
  # Create an encoder/decoder.
35
39
  #
36
40
  # Setup could be moderately expensive due to key derivation; you are recommended to cache
37
- # and reuse instances with equal parameters (e.g. setup once per model)
41
+ # and reuse instances with equal parameters (e.g. setup the key generation once per runtime).
42
+ #
43
+ # * The stringified `prefix` is included in key derivation. It may be nil or empty, in which
44
+ # case the separator is ignored and a bare param will be produced.
38
45
  #
39
- # * `prefix` is stringified, and may be nil, producing an empty prefix.
40
- # The prefix is included in the salt for key generation.
46
+ # * `config` is optional and intended for cases where you need finer control than global defaults.
41
47
  #
42
- # * `config` is optional and intended for cases where you needed finer control than global defaults.
48
+ # Mixed character encodings across prefix & separator may raise Encoding::CompatibilityError.
43
49
  #
44
50
  # The simplest typical invocation is `Epithet.new('prefix')`.
45
51
  #
46
52
  def initialize(prefix, config: Epithet.defaults)
47
53
  prefix = String(prefix)
48
- key_salt = [prefix.bytesize, prefix, config.salt.bytesize, config.salt].pack('Q>Z*Q>Z*')
49
- @block58 = Block58.build(16, alphabet: config.alphabet)
50
- @prefix_s = "#{prefix}#{config.separator}"
54
+ @prefix = prefix.empty? ? prefix : prefix + config.separator
55
+ @wire_prefix = @prefix.b
56
+ key_salt = [prefix.bytesize, prefix, config.context.bytesize, config.context].pack('Q>Z*Q>Z*')
57
+ @codec = config.codec
51
58
 
52
59
  cipher_key_len = OpenSSL::Cipher.new(config.cipher).key_len
53
60
  digest_key_len = OpenSSL::Digest.new(config.digest).block_length
54
- cipher_key = config.keygen.generate('epithet:ecb', key_salt, cipher_key_len)
55
- digest_key = config.keygen.generate('epithet:mac', key_salt, digest_key_len)
61
+ cipher_key = config.keygen.generate("epithet:cipher:#{config.cipher}", key_salt, cipher_key_len)
62
+ digest_key = config.keygen.generate("epithet:digest:#{config.digest}", key_salt, digest_key_len)
56
63
 
57
64
  @encryptor = OpenSSL::Cipher.new(config.cipher).encrypt.tap { |c| c.key = cipher_key; c.padding = 0 }
58
65
  @decryptor = OpenSSL::Cipher.new(config.cipher).decrypt.tap { |c| c.key = cipher_key; c.padding = 0 }
59
66
  @hmac = OpenSSL::HMAC.new(digest_key, config.digest)
60
67
  end
61
68
 
62
- # Encode a 64-bit unsigned Integer to a prefixed Base58 string.
69
+ # Encode a 64-bit unsigned integer to a prefixed base58 string.
63
70
  # Raises ArgumentError on invalid values.
64
71
  def encode(id)
65
72
  raise ArgumentError, 'not a 64-bit unsigned integer' unless Integer === id && id.bit_length <= 64 && id >= 0
@@ -71,21 +78,23 @@ class Epithet
71
78
  block = e.update([pt, m].pack('a8a8')) + e.final
72
79
  ct = block.unpack('Q>2').then { (_1 << 64) + _2 }
73
80
 
74
- @prefix_s + @block58.i2s(ct)
81
+ @prefix + @codec.i2s(ct)
75
82
  end
76
83
 
77
- # Decode a prefixed or raw Base58 string to an Integer. Raw inputs are
84
+ # Decode a prefixed or raw base58 string to an integer. The input is
85
+ # stringified and read as bytes, whatever its encoding; raw inputs are
78
86
  # recognised by their exact payload length.
79
87
  #
80
- # Returns the Integer on success, nil if authentication fails.
81
- # Raises ArgumentError on invalid wire format (see Block58#valid?).
88
+ # Returns the integer on success, nil if authentication fails.
89
+ # Raises FormatError on invalid wire format (see Block58#valid?).
82
90
  def decode(s)
83
- s = s.delete_prefix(@prefix_s) unless s.bytesize == @block58.size
84
- raise ArgumentError, 'unexpected format' unless @block58.valid?(s)
91
+ s = String(s).b
92
+ s = s.delete_prefix(@wire_prefix) unless s.bytesize == @codec.size
93
+ raise FormatError, 'unexpected format' unless @codec.valid?(s)
85
94
 
86
95
  d = @decryptor.dup
87
96
  h = @hmac.dup
88
- ct = @block58.s2i(s)
97
+ ct = @codec.s2i(s)
89
98
  block = d.update([ct >> 64, ct].pack('Q>2')) + d.final
90
99
  pt, m = block.unpack('a8a8')
91
100
  id = pt.unpack1('Q>')
@@ -110,28 +119,29 @@ class Epithet
110
119
  # scrypt: { salt: "#{MyApp.name}/#{MyApp.env}" }
111
120
  # )
112
121
  #
113
- # # Retaining already-configured passphrase but updating salt,
122
+ # # Retaining already-configured passphrase but updating context,
114
123
  # # and using a custom separator.
115
124
  # Epithet.configure(
116
125
  # keygen: Epithet.defaults.keygen,
117
- # salt: 'rotation-19',
126
+ # context: 'rotation-19',
118
127
  # separator: '-'
119
128
  # )
120
129
  #
121
130
  # #### Options
122
131
  #
123
132
  # * `:passphrase` - Install new key generator with scrypt-derived key material
124
- # * `:scrypt` - Params for scrypt, merged over `Keygen::DEFAULT_SCRYPT_PARAMS`
125
- # * `:keygen` - Install an existing key generator
133
+ # * `:scrypt` - Merge params for scrypt
134
+ # * `:keygen` - Use an existing key generator
126
135
  # * `:cipher` - Must be a 128-bit block cipher in ECB mode or equivalent; omit for standard `aes-256-ecb`
127
- # * `:digest` - Must be >= 64 bits; omit for standard `sha256`
128
- # * `:separator` - String inserted between the prefix and the generated param; omit for standard `_`.
129
- # May be `nil`. Must not share bytes with the alphabet.
130
- # * `:alphabet` - Alphabet for the wire encoding; must be 58 strictly ascending bytes; omit for `Block58::Alphabet`.
131
- # * `:salt` - If supplied, stringified form is included in subkey derivation
136
+ # * `:digest` - Must be >= 64 bits digest; omit for standard `sha256`
137
+ # * `:separator` - String inserted between the prefix and the generated param.
138
+ # Omit for standard `_`. May be `nil`. Must not share bytes with the alphabet.
139
+ # Not emitted when prefix is `nil` or empty.
140
+ # * `:alphabet` - Custom base58 alphabet for the wire encoding. Must be strictly ascending bytes.
141
+ # * `:context` - If supplied, string form is included in subkey derivation.
142
+ # Useful for purpose separation, or rotation epochs.
132
143
  #
133
144
  # At minimum, one of `passphrase:` or `keygen:` is required.
134
- # Configuration via `passphrase` is recommended.
135
145
  #
136
146
  # If passing an existing key generator, the object must respond to `generate(info, salt, length)`
137
147
  # and return a byte string suitable for use with OpenSSL cryptographic primitives.
@@ -162,27 +172,28 @@ class Epithet
162
172
 
163
173
  # Class for passing around preset configs. See Epithet::configure for options.
164
174
  class Config
165
- attr_reader :keygen, :salt, :separator, :alphabet, :cipher, :digest # :nodoc:
175
+ attr_reader :keygen, :context, :separator, :cipher, :digest, :codec # :nodoc:
166
176
 
167
177
  def initialize(opts = {})
168
178
  opts = opts.dup
169
179
  @separator = -String(opts.delete(:separator) { '_' })
170
- @salt = -String(opts.delete(:salt))
171
- @alphabet = -String(opts.delete(:alphabet) { Block58::Alphabet })
172
- @cipher = -(opts.delete(:cipher) || 'aes-256-ecb')
173
- @digest = -(opts.delete(:digest) || 'sha256')
180
+ @context = -String(opts.delete(:context))
181
+ alphabet = String(opts.delete(:alphabet) { Block58::Alphabet })
182
+ @cipher = -(opts.delete(:cipher) || 'aes-256-ecb').downcase
183
+ @digest = -(opts.delete(:digest) || 'sha256').downcase
184
+ keygen, passphrase, scrypt = %i[keygen passphrase scrypt].map { opts.delete it }
174
185
 
175
186
  cipher = OpenSSL::Cipher.new(@cipher)
176
- raise ArgumentError, 'separator intersects alphabet' if @separator.bytes.intersect?(@alphabet.bytes)
187
+ raise ArgumentError, 'separator intersects alphabet' if @separator.bytes.intersect?(alphabet.bytes)
177
188
  raise ArgumentError, "#{@cipher} not a 128-bit block cipher" if cipher.block_size != 16
178
189
  raise ArgumentError, "#{@cipher} requires an IV/nonce" if cipher.iv_len != 0
179
190
  raise ArgumentError, "#{@digest} produces < 64-bit digest" if OpenSSL::Digest.new(@digest).digest_length < 8
180
-
181
- @keygen = opts.delete(:keygen) || Keygen.new(
182
- passphrase: opts.delete(:passphrase),
183
- digest: @digest,
184
- scrypt: opts.delete(:scrypt) || {})
191
+ raise ArgumentError, 'use keygen: or passphrase:, not both' if keygen && (passphrase || scrypt)
192
+ raise ArgumentError, 'one of passphrase: or keygen: is required' unless keygen || passphrase
185
193
  raise ArgumentError, "unused option(s) #{opts.keys}" unless opts.empty?
194
+
195
+ @codec = Block58.build(cipher.block_size, alphabet:)
196
+ @keygen = keygen || Keygen.new(passphrase:, digest: @digest, scrypt:)
186
197
  freeze
187
198
  end
188
199
  end
@@ -196,26 +207,25 @@ class Epithet
196
207
  # salt: 'epithet-default',
197
208
  # N: 1 << 17,
198
209
  # r: 8,
199
- # p: 1,
200
- # length: 32
210
+ # p: 1
201
211
  # }.freeze
202
212
  # ```
203
213
  DEFAULT_SCRYPT_PARAMS = {
204
214
  salt: 'epithet-default',
205
215
  N: 1 << 17,
206
216
  r: 8,
207
- p: 1,
208
- length: 32
217
+ p: 1
209
218
  }.freeze
210
219
 
211
220
  # Create a new key generator from either high-entropy key material, or a supplied passphrase.
212
- # Supplied scrypt params are merged over DEFAULT_SCRYPT_PARAMS.
221
+ # Supplied scrypt params, if any, are merged over DEFAULT_SCRYPT_PARAMS.
213
222
  def initialize(ikm: nil, passphrase: nil, digest: 'sha256', scrypt: {})
214
223
  if (passphrase.nil? && ikm.nil?) || (!passphrase.nil? && !ikm.nil?)
215
224
  raise ArgumentError, 'keygen requires either ikm or passphrase'
216
225
  end
226
+ raise ArgumentError, 'scrypt length is not configurable' if scrypt&.key?(:length)
217
227
 
218
- @ikm = (ikm ? ikm.b : OpenSSL::KDF.scrypt(passphrase, **DEFAULT_SCRYPT_PARAMS, **scrypt)).freeze
228
+ @ikm = (ikm&.b || OpenSSL::KDF.scrypt(passphrase, **DEFAULT_SCRYPT_PARAMS, **scrypt, length: 32)).freeze
219
229
  @digest = -String(digest)
220
230
  freeze
221
231
  end
@@ -226,11 +236,11 @@ class Epithet
226
236
 
227
237
  # Derive a key via HKDF.
228
238
  def generate(info, salt, length)
229
- OpenSSL::KDF.hkdf(@ikm, hash: @digest, info: info, salt: salt, length: length)
239
+ OpenSSL::KDF.hkdf(@ikm, hash: @digest, info:, salt:, length:)
230
240
  end
231
241
  end
232
242
 
233
- # Fixed-length Base58 codec for a fixed-size block.
243
+ # Fixed-length base58 codec for a fixed-size block.
234
244
  #
235
245
  # Obtain codecs via Block58::build, which selects the fastest variant for
236
246
  # the block size, an unrolled decoder for 16-byte blocks, or the generic
@@ -239,7 +249,7 @@ class Epithet
239
249
  # `= '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'`
240
250
  Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
241
251
 
242
- POW58 = Array.new(11) { 58**_1 }.freeze # :nodoc:
252
+ POW58 = Array.new(11) { 58**it }.freeze # :nodoc:
243
253
 
244
254
  attr_reader :size
245
255
 
@@ -255,11 +265,12 @@ class Epithet
255
265
  @alphabet = alphabet.b.freeze
256
266
  raise ArgumentError, 'invalid alphabet length' unless @alphabet.bytesize == 58
257
267
  raise ArgumentError, 'alphabet not strictly ascending' unless @alphabet.bytes.each_cons(2).all? { _2 > _1 }
258
- @size = ((block_size * 8) / Math.log2(58)).ceil(0)
268
+ @size = ((block_size * 8) / Math.log2(58)).ceil
259
269
  @charsel = @alphabet.gsub(/[\^\-\\]/, '\\\\\&').freeze
260
270
  @blank = @alphabet[0] * @size
261
271
  @lut = @alphabet.each_byte.with_index.with_object("\0" * 256) { |(val, idx), lut| lut.setbyte(val, idx) }.freeze
262
- @max = i2s((1 << (block_size * 8)) - 1).freeze
272
+ @limit = 1 << (block_size * 8)
273
+ @max = i2s(@limit - 1).freeze
263
274
  end
264
275
 
265
276
  def inspect
@@ -267,13 +278,15 @@ class Epithet
267
278
  end
268
279
 
269
280
  # Return true if the string is in range with the right size and alphabet.
281
+ # The input is read as bytes, whatever its encoding.
270
282
  def valid?(s)
271
- String === s && s.bytesize == @size && s <= @max && s.count(@charsel) == @size
283
+ String === s && s.bytesize == @size && (s = s.b) <= @max && s.count(@charsel) == @size
272
284
  end
273
285
 
274
- # Encode a non-negative Integer to fixed-length Base58.
275
- # Truncates if int >= 58**size.
286
+ # Encode an acceptable integer to fixed-length base58.
276
287
  def i2s(int)
288
+ raise ArgumentError, 'integer out of block range' unless Integer === int && int >= 0 && int < @limit
289
+
277
290
  # Using divmod+setbyte is faster than Integer#digits under YJIT,
278
291
  # and about equal in plain MRI.
279
292
  alphabet = @alphabet
@@ -288,8 +301,8 @@ class Epithet
288
301
  out
289
302
  end
290
303
 
291
- # Decode a fixed-length Base58 string to an Integer.
292
- # Assumes the input passes `#valid?`. Wraps at 58**size on the i2s round trip.
304
+ # Decode a fixed-length base58 string to an integer.
305
+ # Assumes the input passes `#valid?`, behaviour undefined if it doesn't.
293
306
  def s2i(str)
294
307
  # Chunking intermediate results into 64-bit integers is ~5x faster
295
308
  # under YJIT than Horner's scheme
@@ -324,14 +337,14 @@ class Epithet
324
337
  raise ArgumentError, 'unrolled codec requires a 16-byte block' unless @size == 22
325
338
  end
326
339
 
327
- # Decode a fixed-length Base58 string to an Integer.
328
- # Assumes the input passes `#valid?`.
340
+ # Decode a 22-digit base58 string to an integer.
341
+ # Assumes the input passes `#valid?`, behaviour undefined if it doesn't.
329
342
  def s2i(str)
330
343
  # rubocop:disable Style/NumericLiterals, Lint/AmbiguousOperatorPrecedence, Layout
331
344
  #
332
- # By unrolling the chunks against literal coefficients, this is ~1.6x
333
- # faster under YJIT than the generic chunked Block58#s2i, and ~8x
334
- # faster than Horner's scheme.
345
+ # By unrolling the chunks against literal coefficients, this tested with Ruby 4.0
346
+ # at ~1.5x faster under YJIT than the generic chunked Block58#s2i, and ~6x faster
347
+ # than Horner's scheme.
335
348
  lut = @lut
336
349
 
337
350
  acc0 = lut.getbyte(str.getbyte(0)) * 7427658739644928 +
@@ -356,10 +369,10 @@ class Epithet
356
369
  lut.getbyte(str.getbyte(18)) * 58 +
357
370
  lut.getbyte(str.getbyte(19))
358
371
 
359
- lut.getbyte(str.getbyte(21)) +
360
- 58 * lut.getbyte(str.getbyte(20)) +
361
- 3364 * acc1 +
362
- 1449225352009601191936 * acc0
372
+ lut.getbyte(str.getbyte(21)) +
373
+ lut.getbyte(str.getbyte(20)) * 58 +
374
+ acc1 * 3364 +
375
+ acc0 * 1449225352009601191936
363
376
 
364
377
  # rubocop:enable Style/NumericLiterals, Lint/AmbiguousOperatorPrecedence, Layout
365
378
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: epithet
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.0
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Josh Goodall
@@ -65,7 +65,7 @@ dependencies:
65
65
  - - ">="
66
66
  - !ruby/object:Gem::Version
67
67
  version: '0'
68
- description: Epithet generates stable, prefixed, Base58 identifiers from 64-bit integers
68
+ description: Epithet generates stable, prefixed, base58 identifiers from 64-bit integers
69
69
  using AES and HMAC.
70
70
  email:
71
71
  - inopinatus@hey.com
@@ -96,7 +96,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
96
96
  requirements:
97
97
  - - ">="
98
98
  - !ruby/object:Gem::Version
99
- version: '3.3'
99
+ version: '3.4'
100
100
  required_rubygems_version: !ruby/object:Gem::Requirement
101
101
  requirements:
102
102
  - - ">="
@@ -105,5 +105,5 @@ required_rubygems_version: !ruby/object:Gem::Requirement
105
105
  requirements: []
106
106
  rubygems_version: 4.0.10
107
107
  specification_version: 4
108
- summary: External base58 identifiers with reversible, authenticated obfuscation.
108
+ summary: External base58 identifiers with reversible, tamper-evident obfuscation.
109
109
  test_files: []