MCPcopy Index your code
hub / github.com/nodejs/node / testDecapsulateKey

Function testDecapsulateKey

test/parallel/test-webcrypto-encap-decap-ml-kem.js:138–228  ·  view source on GitHub ↗
({ name, publicKeyPem, privateKeyPem, results })

Source from the content-addressed store, hash-verified

136}
137
138async function testDecapsulateKey({ name, publicKeyPem, privateKeyPem, results }) {
139 const [
140 publicKey,
141 privateKey,
142 noDecapsulatePrivateKey,
143 ] = await Promise.all([
144 crypto.createPublicKey(publicKeyPem)
145 .toCryptoKey(name, false, ['encapsulateKey']),
146 crypto.createPrivateKey(privateKeyPem)
147 .toCryptoKey(name, false, ['decapsulateKey']),
148 crypto.createPrivateKey(privateKeyPem)
149 .toCryptoKey(name, false, ['decapsulateBits']),
150 ]);
151
152 // Test successful round-trip: encapsulate then decapsulate
153 const encapsulated = await subtle.encapsulateKey(
154 { name },
155 publicKey,
156 'HKDF',
157 false,
158 ['deriveBits']
159 );
160
161 const decapsulatedKey = await subtle.decapsulateKey(
162 { name },
163 privateKey,
164 encapsulated.ciphertext,
165 'HKDF',
166 false,
167 ['deriveBits']
168 );
169
170 assert(decapsulatedKey instanceof CryptoKey);
171 assert.strictEqual(decapsulatedKey.type, 'secret');
172 assert.strictEqual(decapsulatedKey.algorithm.name, 'HKDF');
173 assert.strictEqual(decapsulatedKey.extractable, false);
174 assert.deepStrictEqual(decapsulatedKey.usages, ['deriveBits']);
175
176 // Verify the keys are the same by using KeyObject.from() and comparing
177 const originalKeyData = KeyObject.from(encapsulated.sharedKey).export();
178 const decapsulatedKeyData = KeyObject.from(decapsulatedKey).export();
179 assert(originalKeyData.equals(decapsulatedKeyData));
180
181 const decapsulatedHmac = await subtle.decapsulateKey(
182 { name },
183 privateKey,
184 encapsulated.ciphertext,
185 { name: 'HMAC', hash: 'SHA-256', length: 255 },
186 false,
187 ['sign', 'verify']
188 );
189 assert.strictEqual(decapsulatedHmac.algorithm.name, 'HMAC');
190 assert.strictEqual(decapsulatedHmac.algorithm.length, 255);
191 assert.strictEqual(getCryptoKeyData(decapsulatedHmac).length, 32);
192 assert.strictEqual(getCryptoKeyData(decapsulatedHmac)[31] & 0b00000001, 0);
193
194 // Test with test vector ciphertext and expected shared key
195 const vectorDecapsulatedKey = await subtle.decapsulateKey(

Calls 7

getCryptoKeyDataFunction · 0.85
allMethod · 0.80
toCryptoKeyMethod · 0.80
assertFunction · 0.50
exportMethod · 0.45
fromMethod · 0.45
equalsMethod · 0.45

Tested by

no test coverage detected