nuckle 0.2.1 → 0.4.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: b6a034f12d9a0dd8326bfbc7595b593cd7a0089ab7fe0c8563c7d7eecce791e9
4
- data.tar.gz: 6161d94c79b134ffe0dd014dba44c65345910bde408ab5c618fccba456cc5356
3
+ metadata.gz: c5e6f2dd3c188bdd913b913406835a4f1a316bbc67bb5df1f45abacea0e0a269
4
+ data.tar.gz: dfc1c52875126816b9d65d39a664340ff0e3cdb7b6bffc7c0634007e8b5eef40
5
5
  SHA512:
6
- metadata.gz: e513c94f45a9bf21e6a432c419868e8c5817bd82c7727debf402394dfd09d28fa488f8622ba69182e44d30e7262caa8b5ac6263e06ccddb6f7e96864da535063
7
- data.tar.gz: dc9dbc2a4f101c1bc842037b88f3db9dd765020c5e3d855f6ad4c45c26847aa79e278ebcb0a410f4a4a216fd551d063b37ea5cf432996b867c031e478e9b5a00
6
+ metadata.gz: 2a9780a5aae93b1eabbcc9917fa05930342712b56f2719c5205d5cbfbd8f232d9d0b912fa2c3d08fec4bbc9181f46727dc8678a8c1c18e5ecb5eeafa8641815e
7
+ data.tar.gz: af0a0dedac64cc08da2cdbd9ebcdaa478ea66dd9b876dac3f9f06f615883c1f0d7e29b3dabe1424a6638c0418d39c402d3fd3ce455b5e46bb1a496d219134fdc
data/README.md CHANGED
@@ -28,9 +28,12 @@ through timing side channels. Use
28
28
  |-----------|-------------|
29
29
  | **Curve25519** | Elliptic-curve Diffie-Hellman (key agreement) |
30
30
  | **XSalsa20** | Extended-nonce stream cipher (includes HSalsa20, Salsa20) |
31
+ | **ChaCha20** | Stream cipher (DJB's 8-byte-nonce variant) |
31
32
  | **Poly1305** | One-time message authenticator |
33
+ | **BLAKE3** | Cryptographic hash — unkeyed, keyed, `derive_key`, XOF |
32
34
  | **Box** | Public-key authenticated encryption (Curve25519-XSalsa20-Poly1305) |
33
35
  | **SecretBox** | Symmetric authenticated encryption (XSalsa20-Poly1305) |
36
+ | **ChaCha20-BLAKE3** | Authenticated encryption AEAD, wire-compatible with [skerkour/chacha20-blake3](https://github.com/skerkour/chacha20-blake3) |
34
37
 
35
38
  ## Usage
36
39
 
@@ -71,11 +74,37 @@ If you know what you're doing:
71
74
  RbNaCl = Nuckle
72
75
  ```
73
76
 
77
+ ## Performance
78
+
79
+ Pure Ruby versus the native equivalents (`rbnacl`/libsodium, `blake3-rb`,
80
+ `chacha20blake3`). Ruby 4.0.2 with YJIT, on a single core.
81
+ Numbers are slowdown factors (smaller = closer to native);
82
+ run `bundle exec ruby --yjit bench/primitives.rb` to reproduce.
83
+
84
+ | Primitive | 256 B | 1 KB | 4 KB | 16 KB |
85
+ | ------------------------------- | -----: | -----: | -----: | -----: |
86
+ | BLAKE3 hash | 46× | 118× | 340× | 716× |
87
+ | Poly1305 MAC | 31× | 83× | 161× | 221× |
88
+ | SecretBox (XSalsa20-Poly1305) | 40× | 65× | 123× | 166× |
89
+ | Box (Curve25519-XSalsa20-Poly.) | 46× | 73× | 125× | 162× |
90
+ | ChaCha20-BLAKE3 AEAD | 108× | 159× | 242× | 323× |
91
+
92
+ Size-independent: Curve25519 scalar multiplication ~42× slower; full
93
+ keypair generation ~45× slower.
94
+
95
+ XSalsa20 and ChaCha20 stream ciphers have no direct `rbnacl` counterpart,
96
+ so no comparison is shown; nuckle runs them at roughly 30 k ops/s at 256 B
97
+ and 550 ops/s at 16 KB.
98
+
74
99
  ## Verification
75
100
 
76
- All primitives are tested against rbnacl/libsodium test vectors
77
- (NaCl distribution, RFC 7748, RFC 8439) and cross-validated to
78
- produce byte-identical output.
101
+ Known-answer tests: the NaCl distribution vectors (Box, SecretBox),
102
+ RFC 7748 section 5.2 (X25519, including 1,000 iterations), RFC 8439
103
+ (ChaCha20 block, Poly1305 section 2.5.2 and appendix A.3), the official
104
+ BLAKE3 `test_vectors.json` (all three modes, extended output) and the
105
+ upstream chacha20-blake3 vectors. When the gems are installed, the
106
+ tests also check for byte-identical output against rbnacl/libsodium,
107
+ `blake3-rb` and `chacha20blake3`.
79
108
 
80
109
  ## License
81
110
 
data/lib/nuckle/box.rb CHANGED
@@ -15,12 +15,15 @@ module Nuckle
15
15
 
16
16
  # @param public_key [PublicKey, String] peer's 32-byte public key
17
17
  # @param private_key [PrivateKey, String] own 32-byte private key
18
+ # @raise [CryptoError] if +public_key+ is a low-order point. RbNaCl
19
+ # raises the same error, but only on the first encrypt or decrypt.
20
+ # @raise [TypeError] if a key is the wrong type, e.g. the two are swapped
18
21
  def initialize(public_key, private_key)
19
- pk = extract_bytes(public_key, PUBLICKEYBYTES, "public key")
20
- sk = extract_bytes(private_key, PRIVATEKEYBYTES, "private key")
22
+ public_key = PublicKey.new(public_key) unless public_key.is_a?(PublicKey)
23
+ private_key = PrivateKey.new(private_key) unless private_key.is_a?(PrivateKey)
21
24
 
22
25
  # Compute shared secret via Curve25519 DH
23
- shared = Internals::Curve25519.scalarmult(sk, pk)
26
+ shared = private_key.diffie_hellman(public_key)
24
27
 
25
28
  # Derive symmetric key via HSalsa20 (the "beforenm" step)
26
29
  key = Internals::Salsa20.hsalsa20(shared, "\x00" * 16)
@@ -45,21 +48,5 @@ module Nuckle
45
48
 
46
49
  alias box encrypt
47
50
  alias open decrypt
48
-
49
- private
50
-
51
- def extract_bytes(key, expected_size, name)
52
- bytes = case key
53
- when PublicKey, PrivateKey
54
- key.to_s
55
- when String
56
- key.b
57
- else
58
- raise ArgumentError, "#{name} must be a Key or String"
59
- end
60
- raise ArgumentError, "#{name} must be #{expected_size} bytes (got #{bytes.bytesize})" unless bytes.bytesize == expected_size
61
-
62
- bytes
63
- end
64
51
  end
65
52
  end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nuckle
4
+ # ChaCha20-BLAKE3 authenticated encryption with associated data (AEAD).
5
+ #
6
+ # Wire-compatible with the `chacha20-blake3` Rust crate
7
+ # (https://github.com/skerkour/chacha20-blake3). Given a 32-byte master key
8
+ # and a 24-byte nonce:
9
+ #
10
+ # 1. BLAKE3-keyed(master_key) absorbing the nonce, then XOF-extracting 72
11
+ # bytes, splits into (encryption_key, authentication_key, chacha20_nonce)
12
+ # of sizes (32, 32, 8).
13
+ # 2. Encrypt plaintext with ChaCha20(encryption_key, chacha20_nonce).
14
+ # 3. Tag = BLAKE3-keyed(authentication_key) over
15
+ # aad || u64_le(aad.bytesize) || ciphertext || u64_le(ciphertext.bytesize).
16
+ # 4. Output is `ciphertext || tag`.
17
+ #
18
+ module Chacha20Blake3
19
+ KEYBYTES = 32
20
+ NONCEBYTES = 24
21
+ TAGBYTES = 32
22
+
23
+ # Authenticated encryption cipher.
24
+ class Cipher
25
+ # @param key [String] 32-byte master key
26
+ def initialize(key)
27
+ key = key.b
28
+ raise LengthError, "key must be #{KEYBYTES} bytes (got #{key.bytesize})" unless key.bytesize == KEYBYTES
29
+
30
+ @key = key
31
+ end
32
+
33
+ # Encrypt plaintext with the given 24-byte nonce.
34
+ #
35
+ # @param nonce [String] 24-byte nonce
36
+ # @param plaintext [String]
37
+ # @param aad [String] associated data (authenticated but not encrypted)
38
+ # @return [String] ciphertext || 32-byte tag
39
+ #
40
+ def encrypt(nonce, plaintext, aad: "")
41
+ enc_key, auth_key, enc_nonce = derive_subkeys(nonce)
42
+ ct = Internals::Chacha20.xor(enc_key, enc_nonce, plaintext)
43
+ tag = compute_tag(auth_key, aad, ct)
44
+ ct + tag
45
+ end
46
+
47
+ # Decrypt a ciphertext||tag blob with the given 24-byte nonce.
48
+ #
49
+ # @param nonce [String] 24-byte nonce
50
+ # @param ciphertext [String] ciphertext || 32-byte tag
51
+ # @param aad [String]
52
+ # @return [String] plaintext
53
+ # @raise [CryptoError] on authentication failure
54
+ #
55
+ def decrypt(nonce, ciphertext, aad: "")
56
+ ciphertext = ciphertext.b
57
+ raise CryptoError, "ciphertext too short" if ciphertext.bytesize < TAGBYTES
58
+
59
+ tag = ciphertext.byteslice(ciphertext.bytesize - TAGBYTES, TAGBYTES)
60
+ ct = ciphertext.byteslice(0, ciphertext.bytesize - TAGBYTES)
61
+ decrypt_detached(nonce, ct, tag, aad: aad)
62
+ end
63
+
64
+ # Encrypt, returning ciphertext and tag separately.
65
+ #
66
+ # @return [Array(String, String)] [ciphertext, tag]
67
+ def encrypt_detached(nonce, plaintext, aad: "")
68
+ enc_key, auth_key, enc_nonce = derive_subkeys(nonce)
69
+ ct = Internals::Chacha20.xor(enc_key, enc_nonce, plaintext)
70
+ tag = compute_tag(auth_key, aad, ct)
71
+ [ct, tag]
72
+ end
73
+
74
+ # Decrypt from a detached ciphertext + tag.
75
+ #
76
+ # @raise [CryptoError] on authentication failure
77
+ def decrypt_detached(nonce, ciphertext, tag, aad: "")
78
+ tag = tag.b
79
+ raise LengthError, "tag must be #{TAGBYTES} bytes" unless tag.bytesize == TAGBYTES
80
+
81
+ ciphertext = ciphertext.b
82
+ enc_key, auth_key, enc_nonce = derive_subkeys(nonce)
83
+ expected = compute_tag(auth_key, aad, ciphertext)
84
+ raise CryptoError, "decryption failed" unless Util.verify32(tag, expected)
85
+
86
+ Internals::Chacha20.xor(enc_key, enc_nonce, ciphertext)
87
+ end
88
+
89
+
90
+ # Hides the key bytes, so they stay out of logs and error output.
91
+ #
92
+ # @return [String]
93
+ def inspect
94
+ "#<#{self.class}>"
95
+ end
96
+
97
+ private
98
+
99
+ def derive_subkeys(nonce)
100
+ nonce = nonce.b
101
+ raise LengthError, "nonce must be #{NONCEBYTES} bytes" unless nonce.bytesize == NONCEBYTES
102
+
103
+ kdf = Internals::Blake3.new_keyed(@key).update(nonce).finalize_xof.read(72)
104
+ [kdf.byteslice(0, 32), kdf.byteslice(32, 32), kdf.byteslice(64, 8)]
105
+ end
106
+
107
+ def compute_tag(auth_key, aad, ct)
108
+ aad = aad.b
109
+ Internals::Blake3.new_keyed(auth_key).
110
+ update(aad).
111
+ update([aad.bytesize].pack("Q<")).
112
+ update(ct).
113
+ update([ct.bytesize].pack("Q<")).
114
+ finalize(TAGBYTES)
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,291 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nuckle
4
+ module Internals
5
+ # BLAKE3 cryptographic hash (unkeyed, keyed, and derive_key modes) with XOF.
6
+ #
7
+ # References:
8
+ # - https://github.com/BLAKE3-team/BLAKE3-specs/blob/master/blake3.pdf
9
+ # - https://github.com/BLAKE3-team/BLAKE3 (reference impl)
10
+ #
11
+ module Blake3
12
+ MASK32 = 0xFFFFFFFF
13
+ OUT_LEN = 32
14
+ KEY_LEN = 32
15
+ BLOCK_LEN = 64
16
+ CHUNK_LEN = 1024
17
+
18
+ # Domain-separation flags (per-compression, not global).
19
+ CHUNK_START = 1
20
+ CHUNK_END = 2
21
+ PARENT = 4
22
+ ROOT = 8
23
+ KEYED_HASH = 16
24
+ DERIVE_KEY_CONTEXT = 32
25
+ DERIVE_KEY_MATERIAL = 64
26
+
27
+ # Same constants as SHA-256 IV.
28
+ IV = [
29
+ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
30
+ 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19
31
+ ].freeze
32
+
33
+ # Message-word permutation applied between rounds.
34
+ MSG_PERMUTATION = [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].freeze
35
+
36
+ module_function
37
+
38
+ # Quarter-round (G) on a 16-word state.
39
+ def g(state, a, b, c, d, mx, my)
40
+ state[a] = (state[a] + state[b] + mx) & MASK32
41
+ t = state[d] ^ state[a]
42
+ state[d] = ((t >> 16) | (t << 16)) & MASK32
43
+ state[c] = (state[c] + state[d]) & MASK32
44
+ t = state[b] ^ state[c]
45
+ state[b] = ((t >> 12) | (t << 20)) & MASK32
46
+ state[a] = (state[a] + state[b] + my) & MASK32
47
+ t = state[d] ^ state[a]
48
+ state[d] = ((t >> 8) | (t << 24)) & MASK32
49
+ state[c] = (state[c] + state[d]) & MASK32
50
+ t = state[b] ^ state[c]
51
+ state[b] = ((t >> 7) | (t << 25)) & MASK32
52
+ end
53
+
54
+ def round(state, m)
55
+ # Columns
56
+ g(state, 0, 4, 8, 12, m[0], m[1])
57
+ g(state, 1, 5, 9, 13, m[2], m[3])
58
+ g(state, 2, 6, 10, 14, m[4], m[5])
59
+ g(state, 3, 7, 11, 15, m[6], m[7])
60
+ # Diagonals
61
+ g(state, 0, 5, 10, 15, m[8], m[9])
62
+ g(state, 1, 6, 11, 12, m[10], m[11])
63
+ g(state, 2, 7, 8, 13, m[12], m[13])
64
+ g(state, 3, 4, 9, 14, m[14], m[15])
65
+ end
66
+
67
+ def permute(m)
68
+ MSG_PERMUTATION.map { |i| m[i] }
69
+ end
70
+
71
+ # BLAKE3 compression function.
72
+ #
73
+ # @param cv [Array<Integer>] 8-word chaining value
74
+ # @param block_words [Array<Integer>] 16-word message block
75
+ # @param counter [Integer] 64-bit counter (chunk index, XOF block index, or 0 for parents)
76
+ # @param block_len [Integer] number of valid bytes in the block (1..64, or 0 for empty)
77
+ # @param flags [Integer] domain-separation flags
78
+ # @return [Array<Integer>] 16-word output (first 8 = new CV for non-XOF)
79
+ #
80
+ def compress(cv, block_words, counter, block_len, flags)
81
+ state = [
82
+ cv[0], cv[1], cv[2], cv[3],
83
+ cv[4], cv[5], cv[6], cv[7],
84
+ IV[0], IV[1], IV[2], IV[3],
85
+ counter & MASK32, (counter >> 32) & MASK32, block_len, flags
86
+ ]
87
+ m = block_words.dup
88
+
89
+ round(state, m)
90
+ 6.times do
91
+ m = permute(m)
92
+ round(state, m)
93
+ end
94
+
95
+ # Final xor: state[0..8] ^= state[8..16]; state[8..16] ^= cv[0..8]
96
+ 8.times do |i|
97
+ state[i] ^= state[i + 8]
98
+ state[i + 8] ^= cv[i]
99
+ end
100
+ state
101
+ end
102
+
103
+ # Parse a 64-byte string (or zero-padded short string) into 16 LE u32 words.
104
+ def words_from_block(block)
105
+ block = block + ("\x00".b * (BLOCK_LEN - block.bytesize)) if block.bytesize < BLOCK_LEN
106
+ block.unpack("V16")
107
+ end
108
+
109
+ # Deferred final compression. Supports variable-length output via XOF.
110
+ class Output
111
+ def initialize(input_cv, block_words, counter, block_len, flags)
112
+ @cv = input_cv
113
+ @block = block_words
114
+ @counter = counter
115
+ @block_len = block_len
116
+ @flags = flags
117
+ @xof_ctr = 0
118
+ @buffer = String.new(encoding: Encoding::BINARY)
119
+ end
120
+
121
+ # 8-word CV (non-root). Used when folding intermediate parents.
122
+ def chaining_value
123
+ Blake3.compress(@cv, @block, @counter, @block_len, @flags)[0, 8]
124
+ end
125
+
126
+ # Read the next n bytes from the root XOF stream.
127
+ def read(n)
128
+ out = String.new(capacity: n, encoding: Encoding::BINARY)
129
+ while out.bytesize < n
130
+ if @buffer.empty?
131
+ words = Blake3.compress(@cv, @block, @xof_ctr, @block_len, @flags | ROOT)
132
+ @buffer = words.pack("V16")
133
+ @xof_ctr += 1
134
+ end
135
+ take = [@buffer.bytesize, n - out.bytesize].min
136
+ out << @buffer.byteslice(0, take)
137
+ @buffer = @buffer.byteslice(take..) || "".b
138
+ end
139
+ out
140
+ end
141
+ end
142
+
143
+ # Streaming hasher. Supports update/finalize/finalize_xof.
144
+ class Hasher
145
+ # @param key_words [Array<Integer>] 8-word base key (IV or actual key)
146
+ # @param flags [Integer] base flags (0, KEYED_HASH, or DERIVE_KEY_MATERIAL)
147
+ def initialize(key_words, flags)
148
+ @key_words = key_words.freeze
149
+ @flags = flags
150
+ @cv_stack = []
151
+ @chunk_counter = 0
152
+ @chunk_cv = key_words.dup
153
+ @chunk_block = String.new(encoding: Encoding::BINARY)
154
+ @blocks_compressed = 0
155
+ end
156
+
157
+ # Feed more input. Returns self for chaining.
158
+ def update(input)
159
+ input = input.b
160
+ len = input.bytesize
161
+ offset = 0
162
+
163
+ while offset < len
164
+ if @chunk_block.bytesize == BLOCK_LEN
165
+ if @blocks_compressed < 15
166
+ flush_intermediate_block
167
+ else
168
+ flush_final_chunk_block
169
+ push_and_merge_chunk
170
+ start_new_chunk
171
+ end
172
+ end
173
+
174
+ need = BLOCK_LEN - @chunk_block.bytesize
175
+ take = [need, len - offset].min
176
+ @chunk_block << input.byteslice(offset, take)
177
+ offset += take
178
+ end
179
+ self
180
+ end
181
+
182
+ # Return `out_len` bytes of output (default 32).
183
+ def finalize(out_len = OUT_LEN)
184
+ build_root_output.read(out_len)
185
+ end
186
+
187
+ # Return an Output that can be read incrementally via `read(n)`.
188
+ def finalize_xof
189
+ build_root_output
190
+ end
191
+
192
+ private
193
+
194
+ def flush_intermediate_block
195
+ words = @chunk_block.unpack("V16")
196
+ flags = @flags
197
+ flags |= CHUNK_START if @blocks_compressed == 0
198
+ @chunk_cv = Blake3.compress(@chunk_cv, words, @chunk_counter, BLOCK_LEN, flags)[0, 8]
199
+ @chunk_block = String.new(encoding: Encoding::BINARY)
200
+ @blocks_compressed += 1
201
+ end
202
+
203
+ # Finalize the current (full-size, 16th) block of a chunk and produce its CV.
204
+ def flush_final_chunk_block
205
+ flags = @flags | CHUNK_END
206
+ flags |= CHUNK_START if @blocks_compressed == 0
207
+ words = @chunk_block.unpack("V16")
208
+ @chunk_cv = Blake3.compress(@chunk_cv, words, @chunk_counter, BLOCK_LEN, flags)[0, 8]
209
+ end
210
+
211
+ def push_and_merge_chunk
212
+ completed = @chunk_counter
213
+ @cv_stack.push(@chunk_cv)
214
+ total = completed + 1
215
+ while (total & 1).zero?
216
+ right = @cv_stack.pop
217
+ left = @cv_stack.pop
218
+ block = left + right
219
+ @cv_stack.push(Blake3.compress(@key_words, block, 0, BLOCK_LEN, @flags | PARENT)[0, 8])
220
+ total >>= 1
221
+ end
222
+ end
223
+
224
+ def start_new_chunk
225
+ @chunk_counter += 1
226
+ @chunk_cv = @key_words.dup
227
+ @chunk_block = String.new(encoding: Encoding::BINARY)
228
+ @blocks_compressed = 0
229
+ end
230
+
231
+ # Build the final (deferred) Output — the last compression is not
232
+ # actually performed until root_output#read / chaining_value.
233
+ def build_root_output
234
+ # Current chunk (possibly partial) becomes the right-most subtree.
235
+ flags = @flags | CHUNK_END
236
+ flags |= CHUNK_START if @blocks_compressed == 0
237
+ block_len = @chunk_block.bytesize
238
+ padded = block_len == BLOCK_LEN ? @chunk_block : @chunk_block + ("\x00".b * (BLOCK_LEN - block_len))
239
+ block_words = padded.unpack("V16")
240
+
241
+ output = Output.new(@chunk_cv, block_words, @chunk_counter, block_len, flags)
242
+
243
+ # Fold stack right-to-left; each fold creates a new PARENT Output.
244
+ # The last one (leftmost stack entry) is the root — ROOT flag is
245
+ # applied inside Output#read.
246
+ @cv_stack.reverse_each do |left_cv|
247
+ right_cv = output.chaining_value
248
+ output = Output.new(@key_words, left_cv + right_cv, 0, BLOCK_LEN, @flags | PARENT)
249
+ end
250
+ output
251
+ end
252
+ end
253
+
254
+ # One-shot unkeyed hash.
255
+ #
256
+ # Called with no arguments, this is Object#hash, so the module still
257
+ # works as a Hash key.
258
+ def hash(input = (no_input = true), length = OUT_LEN)
259
+ return super() if no_input
260
+
261
+ Hasher.new(IV, 0).update(input).finalize(length)
262
+ end
263
+
264
+ # Build a Hasher for the unkeyed mode (for streaming use).
265
+ def new_hasher
266
+ Hasher.new(IV, 0)
267
+ end
268
+
269
+ # One-shot keyed hash (32-byte key).
270
+ def keyed_hash(key, input, length = OUT_LEN)
271
+ new_keyed(key).update(input).finalize(length)
272
+ end
273
+
274
+ def new_keyed(key)
275
+ raise LengthError, "key must be 32 bytes" unless key.bytesize == KEY_LEN
276
+
277
+ Hasher.new(key.b.unpack("V8"), KEYED_HASH)
278
+ end
279
+
280
+ # Derive a subkey from a context string and key material.
281
+ def derive_key(context, material, length = OUT_LEN)
282
+ new_derive_key(context).update(material).finalize(length)
283
+ end
284
+
285
+ def new_derive_key(context)
286
+ ctx_key_bytes = Hasher.new(IV, DERIVE_KEY_CONTEXT).update(context).finalize(KEY_LEN)
287
+ Hasher.new(ctx_key_bytes.unpack("V8"), DERIVE_KEY_MATERIAL)
288
+ end
289
+ end
290
+ end
291
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nuckle
4
+ module Internals
5
+ # ChaCha20 stream cipher (DJB's original 8-byte-nonce variant).
6
+ #
7
+ # State layout (16 x 32-bit little-endian words):
8
+ # [ 0.. 3] "expand 32-byte k" constants
9
+ # [ 4..11] 32-byte key
10
+ # [12..13] 64-bit block counter (low word first)
11
+ # [14..15] 8-byte nonce
12
+ #
13
+ # Quarter-round rotations: 16, 12, 8, 7.
14
+ #
15
+ # References:
16
+ # - https://cr.yp.to/chacha/chacha-20080128.pdf (ChaCha family)
17
+ # - RFC 8439 uses the 12-byte-nonce variant; this module implements the
18
+ # 8-byte-nonce variant required by ChaCha20-BLAKE3.
19
+ #
20
+ module Chacha20
21
+ MASK32 = 0xFFFFFFFF
22
+ SIGMA = "expand 32-byte k".b.freeze
23
+ SIGMA_V4 = SIGMA.unpack("V4").freeze
24
+
25
+ module_function
26
+
27
+ # ChaCha20 block function: 20 rounds on 16 x 32-bit words.
28
+ #
29
+ # @param key [String] 32-byte key
30
+ # @param nonce [String] 8-byte nonce
31
+ # @param counter [Integer] 64-bit block counter
32
+ # @return [String] 64-byte keystream block
33
+ #
34
+ def block(key, nonce, counter)
35
+ k0, k1, k2, k3, k4, k5, k6, k7 = key.unpack("V8")
36
+ n0, n1 = nonce.unpack("V2")
37
+ s0, s1, s2, s3 = SIGMA_V4
38
+ c0 = counter & MASK32
39
+ c1 = (counter >> 32) & MASK32
40
+
41
+ x0 = s0; x1 = s1; x2 = s2; x3 = s3
42
+ x4 = k0; x5 = k1; x6 = k2; x7 = k3
43
+ x8 = k4; x9 = k5; x10 = k6; x11 = k7
44
+ x12 = c0; x13 = c1; x14 = n0; x15 = n1
45
+
46
+ z0 = x0; z1 = x1; z2 = x2; z3 = x3
47
+ z4 = x4; z5 = x5; z6 = x6; z7 = x7
48
+ z8 = x8; z9 = x9; z10 = x10; z11 = x11
49
+ z12 = x12; z13 = x13; z14 = x14; z15 = x15
50
+
51
+ 10.times do
52
+ # Column round: QR(0,4,8,12), QR(1,5,9,13), QR(2,6,10,14), QR(3,7,11,15)
53
+ z0 = (z0 + z4) & MASK32; z12 ^= z0; z12 = ((z12 << 16) | (z12 >> 16)) & MASK32
54
+ z8 = (z8 + z12) & MASK32; z4 ^= z8; z4 = ((z4 << 12) | (z4 >> 20)) & MASK32
55
+ z0 = (z0 + z4) & MASK32; z12 ^= z0; z12 = ((z12 << 8) | (z12 >> 24)) & MASK32
56
+ z8 = (z8 + z12) & MASK32; z4 ^= z8; z4 = ((z4 << 7) | (z4 >> 25)) & MASK32
57
+
58
+ z1 = (z1 + z5) & MASK32; z13 ^= z1; z13 = ((z13 << 16) | (z13 >> 16)) & MASK32
59
+ z9 = (z9 + z13) & MASK32; z5 ^= z9; z5 = ((z5 << 12) | (z5 >> 20)) & MASK32
60
+ z1 = (z1 + z5) & MASK32; z13 ^= z1; z13 = ((z13 << 8) | (z13 >> 24)) & MASK32
61
+ z9 = (z9 + z13) & MASK32; z5 ^= z9; z5 = ((z5 << 7) | (z5 >> 25)) & MASK32
62
+
63
+ z2 = (z2 + z6) & MASK32; z14 ^= z2; z14 = ((z14 << 16) | (z14 >> 16)) & MASK32
64
+ z10 = (z10 + z14) & MASK32; z6 ^= z10; z6 = ((z6 << 12) | (z6 >> 20)) & MASK32
65
+ z2 = (z2 + z6) & MASK32; z14 ^= z2; z14 = ((z14 << 8) | (z14 >> 24)) & MASK32
66
+ z10 = (z10 + z14) & MASK32; z6 ^= z10; z6 = ((z6 << 7) | (z6 >> 25)) & MASK32
67
+
68
+ z3 = (z3 + z7) & MASK32; z15 ^= z3; z15 = ((z15 << 16) | (z15 >> 16)) & MASK32
69
+ z11 = (z11 + z15) & MASK32; z7 ^= z11; z7 = ((z7 << 12) | (z7 >> 20)) & MASK32
70
+ z3 = (z3 + z7) & MASK32; z15 ^= z3; z15 = ((z15 << 8) | (z15 >> 24)) & MASK32
71
+ z11 = (z11 + z15) & MASK32; z7 ^= z11; z7 = ((z7 << 7) | (z7 >> 25)) & MASK32
72
+
73
+ # Diagonal round: QR(0,5,10,15), QR(1,6,11,12), QR(2,7,8,13), QR(3,4,9,14)
74
+ z0 = (z0 + z5) & MASK32; z15 ^= z0; z15 = ((z15 << 16) | (z15 >> 16)) & MASK32
75
+ z10 = (z10 + z15) & MASK32; z5 ^= z10; z5 = ((z5 << 12) | (z5 >> 20)) & MASK32
76
+ z0 = (z0 + z5) & MASK32; z15 ^= z0; z15 = ((z15 << 8) | (z15 >> 24)) & MASK32
77
+ z10 = (z10 + z15) & MASK32; z5 ^= z10; z5 = ((z5 << 7) | (z5 >> 25)) & MASK32
78
+
79
+ z1 = (z1 + z6) & MASK32; z12 ^= z1; z12 = ((z12 << 16) | (z12 >> 16)) & MASK32
80
+ z11 = (z11 + z12) & MASK32; z6 ^= z11; z6 = ((z6 << 12) | (z6 >> 20)) & MASK32
81
+ z1 = (z1 + z6) & MASK32; z12 ^= z1; z12 = ((z12 << 8) | (z12 >> 24)) & MASK32
82
+ z11 = (z11 + z12) & MASK32; z6 ^= z11; z6 = ((z6 << 7) | (z6 >> 25)) & MASK32
83
+
84
+ z2 = (z2 + z7) & MASK32; z13 ^= z2; z13 = ((z13 << 16) | (z13 >> 16)) & MASK32
85
+ z8 = (z8 + z13) & MASK32; z7 ^= z8; z7 = ((z7 << 12) | (z7 >> 20)) & MASK32
86
+ z2 = (z2 + z7) & MASK32; z13 ^= z2; z13 = ((z13 << 8) | (z13 >> 24)) & MASK32
87
+ z8 = (z8 + z13) & MASK32; z7 ^= z8; z7 = ((z7 << 7) | (z7 >> 25)) & MASK32
88
+
89
+ z3 = (z3 + z4) & MASK32; z14 ^= z3; z14 = ((z14 << 16) | (z14 >> 16)) & MASK32
90
+ z9 = (z9 + z14) & MASK32; z4 ^= z9; z4 = ((z4 << 12) | (z4 >> 20)) & MASK32
91
+ z3 = (z3 + z4) & MASK32; z14 ^= z3; z14 = ((z14 << 8) | (z14 >> 24)) & MASK32
92
+ z9 = (z9 + z14) & MASK32; z4 ^= z9; z4 = ((z4 << 7) | (z4 >> 25)) & MASK32
93
+ end
94
+
95
+ [
96
+ (z0 + x0) & MASK32, (z1 + x1) & MASK32, (z2 + x2) & MASK32, (z3 + x3) & MASK32,
97
+ (z4 + x4) & MASK32, (z5 + x5) & MASK32, (z6 + x6) & MASK32, (z7 + x7) & MASK32,
98
+ (z8 + x8) & MASK32, (z9 + x9) & MASK32, (z10 + x10) & MASK32, (z11 + x11) & MASK32,
99
+ (z12 + x12) & MASK32, (z13 + x13) & MASK32, (z14 + x14) & MASK32, (z15 + x15) & MASK32,
100
+ ].pack("V16")
101
+ end
102
+
103
+ # XOR message with ChaCha20 keystream.
104
+ #
105
+ # @param key [String] 32-byte key
106
+ # @param nonce [String] 8-byte nonce
107
+ # @param message [String] plaintext/ciphertext
108
+ # @param counter [Integer] initial 64-bit block counter (default 0)
109
+ # @return [String] XOR'd output (same length as message)
110
+ #
111
+ def xor(key, nonce, message, counter = 0)
112
+ msg = message.b
113
+ len = msg.bytesize
114
+ out = String.new(capacity: len, encoding: Encoding::BINARY)
115
+ offset = 0
116
+
117
+ while offset < len
118
+ ks = block(key, nonce, counter)
119
+ remaining = len - offset
120
+ take = remaining < 64 ? remaining : 64
121
+
122
+ if take == 64
123
+ m = msg.byteslice(offset, 64).unpack("Q<8")
124
+ b = ks.unpack("Q<8")
125
+ out << [m[0] ^ b[0], m[1] ^ b[1], m[2] ^ b[2], m[3] ^ b[3],
126
+ m[4] ^ b[4], m[5] ^ b[5], m[6] ^ b[6], m[7] ^ b[7]].pack("Q<8")
127
+ else
128
+ m = msg.byteslice(offset, take).unpack("C*")
129
+ b = ks.unpack("C*")
130
+ take.times { |i| m[i] ^= b[i] }
131
+ out << m.pack("C*")
132
+ end
133
+
134
+ offset += take
135
+ counter += 1
136
+ end
137
+
138
+ out
139
+ end
140
+
141
+ # Generate ChaCha20 keystream bytes (equivalent to XOR against zeros).
142
+ #
143
+ # @param key [String] 32-byte key
144
+ # @param nonce [String] 8-byte nonce
145
+ # @param length [Integer] number of bytes to generate
146
+ # @param counter [Integer] initial 64-bit block counter (default 0)
147
+ # @return [String] keystream bytes
148
+ #
149
+ def stream(key, nonce, length, counter = 0)
150
+ xor(key, nonce, ("\x00".b * length), counter)
151
+ end
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Nuckle
4
+ # Raised when a key, nonce or tag has the wrong length. An ArgumentError,
5
+ # like RbNaCl::LengthError.
6
+ class LengthError < ArgumentError
7
+ end
8
+ end
@@ -15,13 +15,16 @@ module Nuckle
15
15
  end
16
16
 
17
17
 
18
- # @param key [String] 32-byte raw private key (binary)
18
+ # @param key [String, PrivateKey] 32-byte raw private key (binary)
19
+ # @raise [TypeError] if +key+ is neither a PrivateKey nor a String
19
20
  def initialize(key)
20
- key = key.to_s if key.respond_to?(:to_s) && !key.is_a?(String)
21
- key = key.b
22
- raise ArgumentError, "private key must be #{BYTES} bytes (got #{key.bytesize})" unless key.bytesize == BYTES
21
+ key = key.to_s if key.is_a?(PrivateKey)
22
+ raise TypeError, "private key must be a String or #{PrivateKey} (got #{key.class})" unless key.respond_to?(:to_str)
23
23
 
24
- @key = key
24
+ key = key.to_str.b
25
+ raise LengthError, "private key must be #{BYTES} bytes (got #{key.bytesize})" unless key.bytesize == BYTES
26
+
27
+ @key = key.freeze
25
28
  end
26
29
 
27
30
 
@@ -40,26 +43,34 @@ module Nuckle
40
43
  # derivation (no HSalsa20). Callers are responsible for deriving
41
44
  # symmetric keys from the result (e.g. via HKDF or BLAKE3-derive-key).
42
45
  #
46
+ # Like libsodium's crypto_scalarmult, it refuses low-order public keys:
47
+ # those make the shared secret all zero.
48
+ #
43
49
  # @param peer_public_key [PublicKey, String] peer's 32-byte public key
44
50
  # @return [String] 32-byte shared secret (binary)
51
+ # @raise [CryptoError] if the shared secret is all zero
52
+ # @raise [TypeError] if +peer_public_key+ is neither a PublicKey nor a String
45
53
  def diffie_hellman(peer_public_key)
46
- pk = case peer_public_key
47
- when PublicKey
48
- peer_public_key.to_s
49
- when String
50
- peer_public_key.b
51
- else
52
- raise ArgumentError, "peer_public_key must be a PublicKey or String"
53
- end
54
- raise ArgumentError, "peer public key must be 32 bytes" unless pk.bytesize == BYTES
55
-
56
- Internals::Curve25519.scalarmult(@key, pk)
54
+ peer_public_key = PublicKey.new(peer_public_key) unless peer_public_key.is_a?(PublicKey)
55
+
56
+ shared = Internals::Curve25519.scalarmult(@key, peer_public_key.to_s)
57
+ raise CryptoError, "low-order public key (all-zero shared secret)" if Util.zero?(shared)
58
+
59
+ shared
57
60
  end
58
61
 
59
62
 
60
- # @return [String] raw 32-byte key (binary)
63
+ # @return [String] raw 32-byte key (binary, frozen)
61
64
  def to_bytes = @key
62
- # @return [String] raw 32-byte key (binary)
65
+ # @return [String] raw 32-byte key (binary, frozen)
63
66
  def to_s = @key
67
+
68
+
69
+ # Hides the key bytes, so they stay out of logs and error output.
70
+ #
71
+ # @return [String]
72
+ def inspect
73
+ "#<#{self.class}>"
74
+ end
64
75
  end
65
76
  end
@@ -7,22 +7,25 @@ module Nuckle
7
7
  BYTES = 32
8
8
 
9
9
 
10
- # @param key [String] 32-byte raw public key (binary)
10
+ # @param key [String, PublicKey] 32-byte raw public key (binary)
11
+ # @raise [TypeError] if +key+ is neither a PublicKey nor a String
11
12
  def initialize(key)
12
- key = key.to_s if key.respond_to?(:to_s) && !key.is_a?(String)
13
- key = key.b
14
- raise ArgumentError, "public key must be #{BYTES} bytes (got #{key.bytesize})" unless key.bytesize == BYTES
13
+ key = key.to_s if key.is_a?(PublicKey)
14
+ raise TypeError, "public key must be a String or #{PublicKey} (got #{key.class})" unless key.respond_to?(:to_str)
15
15
 
16
- @key = key
16
+ key = key.to_str.b
17
+ raise LengthError, "public key must be #{BYTES} bytes (got #{key.bytesize})" unless key.bytesize == BYTES
18
+
19
+ @key = key.freeze
17
20
  end
18
21
 
19
22
 
20
- # @return [String] raw 32-byte key (binary)
23
+ # @return [String] raw 32-byte key (binary, frozen)
21
24
  def to_bytes = @key
22
- # @return [String] raw 32-byte key (binary)
25
+ # @return [String] raw 32-byte key (binary, frozen)
23
26
  def to_s = @key
24
27
 
25
- # Constant-time equality comparison.
28
+ # Equality without an early exit (see {Util.verify}).
26
29
  #
27
30
  # @param other [PublicKey] key to compare
28
31
  # @return [Boolean]
@@ -16,7 +16,7 @@ module Nuckle
16
16
  # @param key [String] 32-byte symmetric key (binary)
17
17
  def initialize(key)
18
18
  key = key.b
19
- raise ArgumentError, "key must be #{KEYBYTES} bytes (got #{key.bytesize})" unless key.bytesize == KEYBYTES
19
+ raise LengthError, "key must be #{KEYBYTES} bytes (got #{key.bytesize})" unless key.bytesize == KEYBYTES
20
20
 
21
21
  @key = key
22
22
  end
@@ -36,7 +36,7 @@ module Nuckle
36
36
  def encrypt(nonce, plaintext)
37
37
  nonce = nonce.b
38
38
  plaintext = plaintext.b
39
- raise ArgumentError, "nonce must be #{NONCEBYTES} bytes" unless nonce.bytesize == NONCEBYTES
39
+ raise LengthError, "nonce must be #{NONCEBYTES} bytes" unless nonce.bytesize == NONCEBYTES
40
40
 
41
41
  # Pad with 32 zero bytes
42
42
  padded = ("\x00" * ZEROBYTES + plaintext).b
@@ -63,7 +63,7 @@ module Nuckle
63
63
  def decrypt(nonce, ciphertext)
64
64
  nonce = nonce.b
65
65
  ciphertext = ciphertext.b
66
- raise ArgumentError, "nonce must be #{NONCEBYTES} bytes" unless nonce.bytesize == NONCEBYTES
66
+ raise LengthError, "nonce must be #{NONCEBYTES} bytes" unless nonce.bytesize == NONCEBYTES
67
67
  raise CryptoError, "ciphertext too short" if ciphertext.bytesize < MACBYTES
68
68
 
69
69
  mac = ciphertext.byteslice(0, MACBYTES)
@@ -86,5 +86,13 @@ module Nuckle
86
86
  # Aliases matching rbnacl API
87
87
  alias box encrypt
88
88
  alias open decrypt
89
+
90
+
91
+ # Hides the key bytes, so they stay out of logs and error output.
92
+ #
93
+ # @return [String]
94
+ def inspect
95
+ "#<#{self.class}>"
96
+ end
89
97
  end
90
98
  end
data/lib/nuckle/util.rb CHANGED
@@ -1,7 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Nuckle
4
- # Constant-time comparison utilities for cryptographic data.
4
+ # Comparison utilities for cryptographic data. They have no early exit,
5
+ # but Ruby gives no constant-time guarantee (see SECURITY.md).
5
6
  module Util
6
7
  # Compare two 16-byte strings.
7
8
  def self.verify16(a, b)
@@ -21,18 +22,33 @@ module Nuckle
21
22
  end
22
23
 
23
24
 
24
- # Compares two binary strings for equality.
25
+ # Compares two strings byte by byte. XORs every byte pair and ORs the
26
+ # results, so unlike String#== it does not stop at the first
27
+ # difference. Lengths are not treated as secret.
25
28
  #
26
29
  # @param a [String] first string
27
30
  # @param b [String] second string
28
31
  # @param expected_size [Integer, nil] required byte length, or nil to skip check
29
32
  # @return [Boolean]
30
33
  def self.verify(a, b, expected_size = nil)
31
- a = a.b if a.encoding != Encoding::BINARY
32
- b = b.b if b.encoding != Encoding::BINARY
33
34
  return false if expected_size && (a.bytesize != expected_size || b.bytesize != expected_size)
35
+ return false unless a.bytesize == b.bytesize
34
36
 
35
- a == b
37
+ diff = 0
38
+ a.bytesize.times { |i| diff |= a.getbyte(i) ^ b.getbyte(i) }
39
+ diff.zero?
40
+ end
41
+
42
+
43
+ # Checks whether every byte is zero. ORs all bytes together, with no
44
+ # early exit.
45
+ #
46
+ # @param bytes [String]
47
+ # @return [Boolean]
48
+ def self.zero?(bytes)
49
+ acc = 0
50
+ bytes.each_byte { |byte| acc |= byte }
51
+ acc.zero?
36
52
  end
37
53
  end
38
54
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Nuckle
4
- VERSION = "0.2.1"
4
+ VERSION = "0.4.0"
5
5
  end
data/lib/nuckle.rb CHANGED
@@ -6,12 +6,16 @@
6
6
 
7
7
  require_relative "nuckle/version"
8
8
  require_relative "nuckle/crypto_error"
9
+ require_relative "nuckle/length_error"
9
10
  require_relative "nuckle/random"
10
11
  require_relative "nuckle/util"
11
12
  require_relative "nuckle/internals/curve25519"
12
13
  require_relative "nuckle/internals/salsa20"
14
+ require_relative "nuckle/internals/chacha20"
13
15
  require_relative "nuckle/internals/poly1305"
16
+ require_relative "nuckle/internals/blake3"
14
17
  require_relative "nuckle/public_key"
15
18
  require_relative "nuckle/private_key"
16
19
  require_relative "nuckle/box"
17
20
  require_relative "nuckle/secret_box"
21
+ require_relative "nuckle/chacha20_blake3"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: nuckle
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.1
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Patrik Wenger
@@ -21,10 +21,14 @@ files:
21
21
  - README.md
22
22
  - lib/nuckle.rb
23
23
  - lib/nuckle/box.rb
24
+ - lib/nuckle/chacha20_blake3.rb
24
25
  - lib/nuckle/crypto_error.rb
26
+ - lib/nuckle/internals/blake3.rb
27
+ - lib/nuckle/internals/chacha20.rb
25
28
  - lib/nuckle/internals/curve25519.rb
26
29
  - lib/nuckle/internals/poly1305.rb
27
30
  - lib/nuckle/internals/salsa20.rb
31
+ - lib/nuckle/length_error.rb
28
32
  - lib/nuckle/private_key.rb
29
33
  - lib/nuckle/public_key.rb
30
34
  - lib/nuckle/random.rb
@@ -49,7 +53,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
49
53
  - !ruby/object:Gem::Version
50
54
  version: '0'
51
55
  requirements: []
52
- rubygems_version: 4.0.6
56
+ rubygems_version: 4.0.20
53
57
  specification_version: 4
54
58
  summary: Pure Ruby NaCl crypto primitives
55
59
  test_files: []