melos 0.0.1

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 85db7b48fd128cb7bb205689c66ae391964b16228d21d3cd7b1e2f941d332a31
4
+ data.tar.gz: d324b915daf2f12f9226f690e9e2a577ab9a34e7235d9088e181e46ffb7d563c
5
+ SHA512:
6
+ metadata.gz: b0c1e2b24240f32c119d10c09f16ccebe2c3442ec6422df9d85d8669dba4b058d331bc22d8eff36aafda228bd86c0d9d75a8f83d4fce8e2ad9727537ee54593d
7
+ data.tar.gz: 3fe93f19e872cb70e313714008065026e41ddc0374029a5d0f50b9f843d24f4b394cae6974205098fbfdde36cbdcd979ddd8c4bf73ce721181b1c602877e1a22
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Ryo Kajiwara
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # Melos
2
+
3
+ a [Messaging Layer Security Protocol](https://www.rfc-editor.org/rfc/rfc9420.html) implementation in Ruby
4
+
5
+ (yes, [an mls gem](https://rubygems.org/gems/mls) happened to exist since 2014, so...)
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'rake/testtask'
2
+ require "bundler/gem_tasks"
3
+
4
+ task :default => [:test]
5
+
6
+ Rake::TestTask.new do |t|
7
+ t.libs << 'lib'
8
+ t.test_files = FileList['test/test*.rb']
9
+ t.verbose = true
10
+ end
@@ -0,0 +1,84 @@
1
+ module Melos::Constants
2
+ module Version
3
+ MLS10 = 0x01
4
+ end
5
+
6
+ module WireFormat
7
+ # 17.2. MLS Wire Formats
8
+ MLS_PUBLIC_MESSAGE = 0x0001
9
+ MLS_PRIVATE_MESSAGE = 0x0002
10
+ MLS_WELCOME = 0x0003
11
+ MLS_GROUP_INFO = 0x0004
12
+ MLS_KEY_PACKAGE = 0x0005
13
+ end
14
+
15
+ module ExtensionType
16
+ # 17.3. MLS Extension Types
17
+ APPLICATION_ID = 0x0001
18
+ RATCHET_TREE = 0x0002
19
+ REQUIRED_CAPABILITIES = 0x0003
20
+ EXTERNAL_PUB = 0x0004
21
+ EXTERNAL_SENDERS = 0x0005
22
+ end
23
+
24
+ module CredentialType
25
+ # 17.5. MLS Credential Types
26
+ BASIC = 0x0001
27
+ X509 = 0x0002
28
+ end
29
+
30
+ module ContentType
31
+ APPLICATION = 0x01
32
+ PROPOSAL = 0x02
33
+ COMMIT = 0x03
34
+ end
35
+
36
+ module SenderType
37
+ MEMBER = 0x01
38
+ EXTERNAL = 0x02
39
+ NEW_MEMBER_PROPOSAL = 0x03
40
+ NEW_MEMBER_COMMIT = 0x04
41
+ end
42
+
43
+ module LeafNodeSource
44
+ KEY_PACKAGE = 0x01
45
+ UPDATE = 0x02
46
+ COMMIT = 0x03
47
+ end
48
+
49
+ module ProposalType
50
+ ADD = 0x0001
51
+ UPDATE = 0x0002
52
+ REMOVE = 0x0003
53
+ PSK = 0x0004
54
+ REINIT = 0x0005
55
+ EXTERNAL_INIT = 0x0006
56
+ GROUP_CONTEXT_EXTENSIONS = 0x0007
57
+
58
+ # used for debug purposes
59
+ NAMES = [
60
+ nil, 'add', 'update', 'remove', 'psk', 'reinit', 'external_init', 'group_context_extensions'
61
+ ]
62
+ end
63
+
64
+ module NodeType
65
+ LEAF = 0x01
66
+ PARENT = 0x02
67
+ end
68
+
69
+ module PSKType
70
+ EXTERNAL = 0x01
71
+ RESUMPTION = 0x02
72
+ end
73
+
74
+ module ResumptionPSKUsage
75
+ APPLICATION = 0x01
76
+ REINIT = 0x02
77
+ BRANCH = 0x03
78
+ end
79
+
80
+ module ProposalOrRefType
81
+ PROPOSAL = 0x01
82
+ REFERENCE = 0x02
83
+ end
84
+ end
@@ -0,0 +1,307 @@
1
+ require 'openssl'
2
+ require 'hpke'
3
+ require_relative 'vec'
4
+
5
+ class Melos::Crypto
6
+ class CipherSuite
7
+ module X25519
8
+ def self.deserialize_public_encapsulation_key(raw)
9
+ OpenSSL::PKey.new_raw_public_key('X25519', raw)
10
+ end
11
+
12
+ def self.deserialize_private_encapsulation_key(raw)
13
+ OpenSSL::PKey.new_raw_private_key('X25519', raw)
14
+ end
15
+
16
+ def self.deserialize_public_signature_key(raw)
17
+ OpenSSL::PKey.new_raw_public_key('ED25519', raw)
18
+ end
19
+
20
+ def self.deserialize_private_signature_key(raw)
21
+ OpenSSL::PKey.new_raw_private_key('ED25519', raw)
22
+ end
23
+
24
+ def self.hash_algorithm
25
+ nil
26
+ end
27
+ end
28
+
29
+ module X448
30
+ def self.deserialize_public_encapsulation_key(raw)
31
+ OpenSSL::PKey.new_raw_public_key('X448', raw)
32
+ end
33
+
34
+ def self.deserialize_private_encapsulation_key(raw)
35
+ OpenSSL::PKey.new_raw_private_key('X448', raw)
36
+ end
37
+
38
+ def self.deserialize_public_signature_key(raw)
39
+ OpenSSL::PKey.new_raw_public_key('ED448', raw)
40
+ end
41
+
42
+ def self.deserialize_private_signature_key(raw)
43
+ OpenSSL::PKey.new_raw_private_key('ED448', raw)
44
+ end
45
+
46
+ def self.hash_algorithm
47
+ nil
48
+ end
49
+ end
50
+
51
+ class EC
52
+ # also would like to depend on HPKE gem...
53
+ def self.deserialize_private_key(secret)
54
+ asn1_seq = OpenSSL::ASN1.Sequence([
55
+ OpenSSL::ASN1.Integer(1),
56
+ OpenSSL::ASN1.OctetString(secret),
57
+ OpenSSL::ASN1.ObjectId(curve_name, 0, :EXPLICIT)
58
+ ])
59
+
60
+ OpenSSL::PKey.read(asn1_seq.to_der)
61
+ end
62
+
63
+ def self.deserialize_public_key(serialized_pk)
64
+ asn1_seq = OpenSSL::ASN1.Sequence([
65
+ OpenSSL::ASN1.Sequence([
66
+ OpenSSL::ASN1.ObjectId("id-ecPublicKey"),
67
+ OpenSSL::ASN1.ObjectId(curve_name)
68
+ ]),
69
+ OpenSSL::ASN1.BitString(serialized_pk)
70
+ ])
71
+
72
+ OpenSSL::PKey.read(asn1_seq.to_der)
73
+ end
74
+
75
+ def self.deserialize_private_encapsulation_key(raw)
76
+ self.deserialize_private_key(raw)
77
+ end
78
+ def self.deserialize_private_signature_key(raw)
79
+ self.deserialize_private_key(raw)
80
+ end
81
+ def self.deserialize_public_encapsulation_key(raw)
82
+ self.deserialize_public_key(raw)
83
+ end
84
+ def self.deserialize_public_signature_key(raw)
85
+ self.deserialize_public_key(raw)
86
+ end
87
+ end
88
+
89
+ class P256 < EC
90
+ def self.curve_name
91
+ 'prime256v1'
92
+ end
93
+
94
+ def self.hash_algorithm
95
+ 'sha256'
96
+ end
97
+ end
98
+
99
+ class P384 < EC
100
+ def self.curve_name
101
+ 'secp384r1'
102
+ end
103
+
104
+ def self.hash_algorithm
105
+ 'sha384'
106
+ end
107
+ end
108
+
109
+ class P521 < EC
110
+ def self.curve_name
111
+ 'secp521r1'
112
+ end
113
+
114
+ def self.hash_algorithm
115
+ 'sha512'
116
+ end
117
+ end
118
+
119
+ attr_accessor :level, :digest, :hpke, :kdf, :pkey
120
+ def initialize(suite_id)
121
+ case suite_id
122
+ when 1 # MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519
123
+ @level = 128
124
+ @digest = OpenSSL::Digest.new('sha256')
125
+ @hpke = HPKE.new(:x25519, :sha256, :sha256, :aes_128_gcm)
126
+ @kdf = @hpke.hkdf
127
+ @pkey = Melos::Crypto::CipherSuite::X25519
128
+ when 2 # MLS_128_DHKEMP256_AES128GCM_SHA256_P256
129
+ @level = 128
130
+ @digest = OpenSSL::Digest.new('sha256')
131
+ @hpke = HPKE.new(:p_256, :sha256, :sha256, :aes_128_gcm)
132
+ @kdf = @hpke.hkdf
133
+ @pkey = Melos::Crypto::CipherSuite::P256
134
+ when 3 # MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519
135
+ @level = 128
136
+ @digest = OpenSSL::Digest.new('sha256')
137
+ @hpke = HPKE.new(:x25519, :sha256, :sha256, :chacha20_poly1305)
138
+ @kdf = @hpke.hkdf
139
+ @pkey = Melos::Crypto::CipherSuite::X25519
140
+ when 4 # MLS_256_DHKEMX448_AES256GCM_SHA512_Ed448
141
+ @level = 256
142
+ @digest = OpenSSL::Digest.new('sha512')
143
+ @hpke = HPKE.new(:x448, :sha512, :sha512, :aes_256_gcm)
144
+ @kdf = @hpke.hkdf
145
+ @pkey = Melos::Crypto::CipherSuite::X448
146
+ when 5 # MLS_256_DHKEMP521_AES256GCM_SHA512_P521
147
+ @level = 256
148
+ @digest = OpenSSL::Digest.new('sha512')
149
+ @hpke = HPKE.new(:p_521, :sha512, :sha512, :aes_256_gcm)
150
+ @kdf = @hpke.hkdf
151
+ @pkey = Melos::Crypto::CipherSuite::P521
152
+ when 6 # MLS_256_DHKEMX448_CHACHA20POLY1305_SHA512_Ed448
153
+ @level = 256
154
+ @digest = OpenSSL::Digest.new('sha512')
155
+ @hpke = HPKE.new(:x448, :sha512, :sha512, :chacha20_poly1305)
156
+ @kdf = @hpke.hkdf
157
+ @pkey = Melos::Crypto::CipherSuite::X448
158
+ when 7 # MLS_256_DHKEMP384_AES256GCM_SHA384_P384
159
+ @level = 256
160
+ @digest = OpenSSL::Digest.new('sha384')
161
+ @hpke = HPKE.new(:p_384, :sha384, :sha384, :aes_256_gcm)
162
+ @kdf = @hpke.hkdf
163
+ @pkey = Melos::Crypto::CipherSuite::P384
164
+ end
165
+ end
166
+ end
167
+
168
+ module Util
169
+ def self.zero_vector(length)
170
+ ([0] * length).pack('C*')
171
+ end
172
+ end
173
+
174
+ def self.ref_hash(suite, label, value)
175
+ ref_hash_input = Melos::Vec.from_string(label) + Melos::Vec.from_string(value)
176
+ suite.digest.digest(ref_hash_input)
177
+ end
178
+
179
+ def self.make_keypackage_ref(suite, value)
180
+ self.ref_hash(suite, "MLS 1.0 KeyPackage Reference", value)
181
+ end
182
+
183
+ def self.make_proposal_ref(suite, value)
184
+ self.ref_hash(suite, "MLS 1.0 Proposal Reference", value)
185
+ end
186
+
187
+ def self.kdf_extract(suite, salt, ikm)
188
+ suite.kdf.extract(salt, ikm)
189
+ end
190
+
191
+ def self.expand_with_label(suite, secret, label, context, length)
192
+ kdf_label = [length].pack('S>') + Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(context)
193
+ suite.kdf.expand(secret, kdf_label, length)
194
+ end
195
+
196
+ def self.derive_secret(suite, secret, label)
197
+ expand_with_label(suite, secret, label, "", suite.kdf.n_h)
198
+ end
199
+
200
+ def self.derive_tree_secret(suite, secret, label, generation, length)
201
+ generation_in_uint32 = [generation].pack('L>')
202
+ expand_with_label(suite, secret, label, generation_in_uint32, length)
203
+ end
204
+
205
+ def self.derive_key_pair(suite, secret)
206
+ pkey = suite.hpke.kem.derive_key_pair(secret)
207
+ if suite.pkey.equal?(Melos::Crypto::CipherSuite::X25519) || suite.pkey.equal?(Melos::Crypto::CipherSuite::X448)
208
+ # is an Edwards curve
209
+ [pkey.raw_private_key, pkey.raw_public_key]
210
+ else
211
+ # is an EC
212
+ [pkey.private_key.to_s(2), pkey.public_key.to_bn.to_s(2)]
213
+ end
214
+ end
215
+
216
+ def self.seal_base(suite, pkr, info, aad, pt)
217
+ context = suite.hpke.setup_base_s(pkr, info)
218
+ enc = context[:enc]
219
+ ctx = context[:context_s]
220
+ ct = ctx.seal(aad, pt)
221
+ [enc, ct]
222
+ end
223
+
224
+ def self.open_base(suite, enc, skr, info, aad, ct)
225
+ ctx = suite.hpke.setup_base_r(enc, skr, info)
226
+ ctx.open(aad, ct)
227
+ end
228
+
229
+ def self.encrypt_with_label(suite, public_key, label, context, plaintext)
230
+ encrypt_context = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(context)
231
+ pkey = suite.pkey.deserialize_public_encapsulation_key(public_key)
232
+ seal_base(suite, pkey, encrypt_context, "", plaintext)
233
+ end
234
+
235
+ def self.decrypt_with_label(suite, private_key, label, context, kem_output, ciphertext)
236
+ encrypt_context = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(context)
237
+ pkey = suite.pkey.deserialize_private_encapsulation_key(private_key)
238
+ open_base(suite, kem_output, pkey, encrypt_context, "", ciphertext)
239
+ end
240
+
241
+ def self.sign_with_label(suite, signature_key, label, content)
242
+ skey = suite.pkey.deserialize_private_signature_key(signature_key)
243
+ sign_content = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(content)
244
+ skey.sign(suite.pkey.hash_algorithm, sign_content)
245
+ end
246
+
247
+ def self.verify_with_label(suite, verification_key, label, content, signature_value)
248
+ vkey = suite.pkey.deserialize_public_signature_key(verification_key)
249
+ sign_content = Melos::Vec.from_string("MLS 1.0 " + label) + Melos::Vec.from_string(content)
250
+ vkey.verify(suite.pkey.hash_algorithm, signature_value, sign_content)
251
+ end
252
+
253
+ def self.mac(suite, key, data)
254
+ OpenSSL::HMAC.digest(suite.digest, key, data)
255
+ end
256
+
257
+ def self.hash(suite, data)
258
+ suite.digest.digest(data)
259
+ end
260
+
261
+ def self.aead_encrypt(suite, key, nonce, aad, plaintext)
262
+ suite.hpke.aead_encrypt(key, nonce, aad, plaintext)
263
+ end
264
+
265
+ def self.aead_decrypt(suite, key, nonce, aad, ciphertext)
266
+ suite.hpke.aead_decrypt(key, nonce, aad, ciphertext)
267
+ end
268
+
269
+ def self.sender_data_key(suite, sender_data_secret, ciphertext)
270
+ ciphertext_sample = ciphertext[0..(suite.kdf.n_h - 1)]
271
+ expand_with_label(suite, sender_data_secret, "key", ciphertext_sample, suite.hpke.n_k)
272
+ end
273
+
274
+ def self.sender_data_nonce(suite, sender_data_secret, ciphertext)
275
+ ciphertext_sample = ciphertext[0..(suite.kdf.n_h - 1)]
276
+ expand_with_label(suite, sender_data_secret, "nonce", ciphertext_sample, suite.hpke.n_n)
277
+ end
278
+
279
+ def self.encapsulation_key_pair_corresponds?(suite, private_key, public_key)
280
+ private_pkey = suite.pkey.deserialize_private_encapsulation_key(private_key)
281
+ public_pkey = suite.pkey.deserialize_public_encapsulation_key(public_key)
282
+ if suite.pkey.equal?(Melos::Crypto::CipherSuite::X25519) || suite.pkey.equal?(Melos::Crypto::CipherSuite::X448)
283
+ # is an Edwards curve; check equality of the raw public key
284
+ private_pkey.raw_public_key == public_pkey.raw_public_key
285
+ else
286
+ # is an EC; check equality of the public key Point
287
+ private_pkey.public_key == public_pkey.public_key
288
+ end
289
+ end
290
+
291
+ def self.signature_key_pair_corresponds?(suite, private_key, public_key)
292
+ private_pkey = suite.pkey.deserialize_private_signature_key(private_key)
293
+ public_pkey = suite.pkey.deserialize_public_signature_key(public_key)
294
+ if suite.pkey.equal?(Melos::Crypto::CipherSuite::X25519) || suite.pkey.equal?(Melos::Crypto::CipherSuite::X448)
295
+ # is an Edwards curve; check equality of the raw public key
296
+ private_pkey.raw_public_key == public_pkey.raw_public_key
297
+ else
298
+ # is an EC; check equality of the public key Point
299
+ private_pkey.public_key == public_pkey.public_key
300
+ end
301
+ end
302
+
303
+ def self.parent_hash(suite, encryption_key, ph_of_parent, sibling_hash)
304
+ parent_hash_input = Melos::Vec.from_string(encryption_key) + Melos::Vec.from_string(ph_of_parent) + Melos::Vec.from_string(sibling_hash)
305
+ Melos::Crypto.hash(suite, parent_hash_input)
306
+ end
307
+ end
@@ -0,0 +1,62 @@
1
+ require_relative 'crypto'
2
+
3
+ module Melos::KeySchedule
4
+ extend self
5
+
6
+ def joiner_secret(suite, init_secret, commit_secret, group_context)
7
+ Melos::Crypto.expand_with_label(
8
+ suite,
9
+ Melos::Crypto.kdf_extract(suite, init_secret, commit_secret),
10
+ "joiner",
11
+ group_context.raw,
12
+ suite.kdf.n_h
13
+ )
14
+ end
15
+
16
+ def welcome_secret(suite, joiner_secret, psk_secret)
17
+ Melos::Crypto.derive_secret(
18
+ suite,
19
+ Melos::Crypto.kdf_extract(suite, joiner_secret, psk_secret), # sometimes written as `member_secret`
20
+ "welcome"
21
+ )
22
+ end
23
+
24
+ def welcome_key_and_nonce(suite, joiner_secret, psk_secret)
25
+ ws = welcome_secret(suite, joiner_secret, psk_secret)
26
+ [
27
+ Melos::Crypto.expand_with_label(suite, ws, "key", "", suite.hpke.n_k),
28
+ Melos::Crypto.expand_with_label(suite, ws, "nonce", "", suite.hpke.n_n)
29
+ ]
30
+ end
31
+
32
+ def epoch_secret(suite, joiner_secret, psk_secret, group_context)
33
+ Melos::Crypto.expand_with_label(
34
+ suite,
35
+ Melos::Crypto.kdf_extract(suite, joiner_secret, psk_secret),
36
+ "epoch",
37
+ group_context.raw,
38
+ suite.kdf.n_h
39
+ )
40
+ end
41
+
42
+ # epoch-derived secrets, from Table 4 in Section 8
43
+ # will be defined as something like:
44
+ # Melos::KeySchedule.sender_data_secret(suite, epoch_secret)
45
+ [
46
+ ['sender data', 'sender_data_secret'],
47
+ ['encryption', 'encryption_secret'],
48
+ ['exporter', 'exporter_secret'],
49
+ ['external', 'external_secret'],
50
+ ['confirm', 'confirmation_key'],
51
+ ['membership', 'membership_key'],
52
+ ['resumption', 'resumption_psk'],
53
+ ['authentication', 'epoch_authenticator'],
54
+ ['init', 'init_secret'] # this is not part of the table but is defined in the same way
55
+ ].each do |tuple|
56
+ label = tuple[0]
57
+ name = tuple[1]
58
+ define_method(name.to_sym, ->(suite, epoch_secret){
59
+ Melos::Crypto.derive_secret(suite, epoch_secret, label)
60
+ })
61
+ end
62
+ end
data/lib/melos/psk.rb ADDED
@@ -0,0 +1,35 @@
1
+ require_relative 'crypto'
2
+
3
+ module Melos::PSK
4
+ extend self
5
+
6
+ # input: array of [(raw PSK ID), (PSK value)]
7
+ def psk_secret(suite, psk_array)
8
+ secret = Melos::Crypto::Util.zero_vector(suite.kdf.n_h)
9
+
10
+ psk_array.each_with_index do |tuple, idx|
11
+ psk_id = Melos::Struct::PreSharedKeyID.new(tuple[0])
12
+ psk_label = Melos::Struct::PSKLabel.create(
13
+ id: psk_id,
14
+ index: idx,
15
+ count: psk_array.count
16
+ )
17
+
18
+ extracted = Melos::Crypto.kdf_extract(
19
+ suite,
20
+ Melos::Crypto::Util.zero_vector(suite.kdf.n_h),
21
+ tuple[1]
22
+ )
23
+ input = Melos::Crypto.expand_with_label(
24
+ suite,
25
+ extracted,
26
+ "derived psk",
27
+ psk_label.raw,
28
+ suite.kdf.n_h
29
+ )
30
+ secret = Melos::Crypto.kdf_extract(suite, input, secret)
31
+ end
32
+
33
+ return secret
34
+ end
35
+ end
@@ -0,0 +1,109 @@
1
+ require_relative 'tree'
2
+ require_relative 'crypto'
3
+
4
+ module Melos::SecretTree
5
+ def self.create(suite, n_leaves, encryption_secret)
6
+ st = Melos::Tree.empty_tree(n_leaves)
7
+ populate_tree(suite, st, encryption_secret)
8
+ st
9
+ end
10
+
11
+ def self.populate_tree(suite, tree, root_secret)
12
+ populate_tree_impl(suite, tree, tree.root, root_secret)
13
+ end
14
+
15
+ def self.populate_tree_impl(suite, tree, index, secret)
16
+ tree.array[index] = {
17
+ 'handshake_ratchet_secret' => Melos::Crypto.expand_with_label(suite, secret, "handshake", "", suite.kdf.n_h),
18
+ 'application_ratchet_secret' => Melos::Crypto.expand_with_label(suite, secret, "application", "", suite.kdf.n_h),
19
+ 'next_handshake_ratchet_secret_generation' => 0,
20
+ 'next_application_ratchet_secret_generation' => 0
21
+ }
22
+ unless Melos::Tree.leaf?(index)
23
+ left_secret = Melos::Crypto.expand_with_label(suite, secret, "tree", "left", suite.kdf.n_h)
24
+ right_secret = Melos::Crypto.expand_with_label(suite, secret, "tree", "right", suite.kdf.n_h)
25
+ populate_tree_impl(suite, tree, Melos::Tree.left(index), left_secret)
26
+ populate_tree_impl(suite, tree, Melos::Tree.right(index), right_secret)
27
+ end
28
+ end
29
+
30
+ def self.ratchet_until_and_get(suite, content_type, tree, leaf_index, generation)
31
+ # TODO: clear the value on tree when getting
32
+ case content_type
33
+ when 0x02, 0x03
34
+ ratchet_handshake_until(suite, tree, leaf_index, generation)
35
+ [
36
+ tree.leaf_at(leaf_index)['handshake_key'],
37
+ tree.leaf_at(leaf_index)['handshake_nonce'],
38
+ generation
39
+ ]
40
+ else
41
+ ratchet_application_until(suite, tree, leaf_index, generation)
42
+ [
43
+ tree.leaf_at(leaf_index)['application_key'],
44
+ tree.leaf_at(leaf_index)['application_nonce'],
45
+ generation
46
+ ]
47
+ end
48
+ end
49
+
50
+ def self.ratchet_and_get(suite, content_type, tree, leaf_index)
51
+ # TODO: clear the value on tree when getting
52
+ case content_type
53
+ when 0x02, 0x03
54
+ ratchet_handshake(suite, tree, leaf_index)
55
+ [
56
+ tree.leaf_at(leaf_index)['handshake_key'],
57
+ tree.leaf_at(leaf_index)['handshake_nonce'],
58
+ tree.leaf_at(leaf_index)['next_handshake_ratchet_secret_generation'] - 1, # returns current generation
59
+ ]
60
+ else
61
+ ratchet_application(suite, tree, leaf_index)
62
+ [
63
+ tree.leaf_at(leaf_index)['application_key'],
64
+ tree.leaf_at(leaf_index)['application_nonce'],
65
+ tree.leaf_at(leaf_index)['next_application_ratchet_secret_generation'] - 1, # returns current generation
66
+ ]
67
+ end
68
+ end
69
+
70
+ def self.ratchet_application_until(suite, tree, leaf_index, generation)
71
+ while (tree.leaf_at(leaf_index)['next_application_ratchet_secret_generation'] <= generation)
72
+ ratchet_application(suite, tree, leaf_index)
73
+ end
74
+ end
75
+
76
+ def self.ratchet_handshake_until(suite, tree, leaf_index, generation)
77
+ raise ArgumentError.new('cannot generate past generation') if generation < tree.leaf_at(leaf_index)['next_handshake_ratchet_secret_generation'] - 1
78
+ # if current generation, do nothing
79
+ while (tree.leaf_at(leaf_index)['next_handshake_ratchet_secret_generation'] <= generation)
80
+ ratchet_handshake(suite, tree, leaf_index)
81
+ end
82
+ end
83
+
84
+ def self.ratchet_application(suite, tree, leaf_index)
85
+ node_index = leaf_index * 2
86
+ generation = tree.array[node_index]['next_application_ratchet_secret_generation']
87
+ application_ratchet_secret = tree.array[node_index]['application_ratchet_secret']
88
+ application_nonce = Melos::Crypto.derive_tree_secret(suite, application_ratchet_secret, "nonce", generation, suite.hpke.n_n)
89
+ application_key = Melos::Crypto.derive_tree_secret(suite, application_ratchet_secret, "key", generation, suite.hpke.n_k)
90
+ next_application_ratchet_secret = Melos::Crypto.derive_tree_secret(suite, application_ratchet_secret, "secret", generation, suite.kdf.n_h)
91
+ tree.array[node_index]['next_application_ratchet_secret_generation'] = generation + 1
92
+ tree.array[node_index]['application_ratchet_secret'] = next_application_ratchet_secret
93
+ tree.array[node_index]['application_nonce'] = application_nonce
94
+ tree.array[node_index]['application_key'] = application_key
95
+ end
96
+
97
+ def self.ratchet_handshake(suite, tree, leaf_index)
98
+ node_index = leaf_index * 2
99
+ generation = tree.array[node_index]['next_handshake_ratchet_secret_generation']
100
+ handshake_ratchet_secret = tree.array[node_index]['handshake_ratchet_secret']
101
+ handshake_nonce = Melos::Crypto.derive_tree_secret(suite, handshake_ratchet_secret, "nonce", generation, suite.hpke.n_n)
102
+ handshake_key = Melos::Crypto.derive_tree_secret(suite, handshake_ratchet_secret, "key", generation, suite.hpke.n_k)
103
+ next_handshake_ratchet_secret = Melos::Crypto.derive_tree_secret(suite, handshake_ratchet_secret, "secret", generation, suite.kdf.n_h)
104
+ tree.array[node_index]['next_handshake_ratchet_secret_generation'] = generation + 1
105
+ tree.array[node_index]['handshake_ratchet_secret'] = next_handshake_ratchet_secret
106
+ tree.array[node_index]['handshake_nonce'] = handshake_nonce
107
+ tree.array[node_index]['handshake_key'] = handshake_key
108
+ end
109
+ end