|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const common = require('../common'); |
| 4 | +if (!common.hasCrypto) |
| 5 | + common.skip('missing crypto'); |
| 6 | + |
| 7 | +const assert = require('assert'); |
| 8 | +const { createPrivateKey, KeyObject } = require('crypto'); |
| 9 | +const fixtures = require('../common/fixtures'); |
| 10 | +const { subtle } = globalThis.crypto; |
| 11 | + |
| 12 | +function der(tag, ...parts) { |
| 13 | + const body = Buffer.concat(parts); |
| 14 | + const length = body.length < 128 ? [body.length] : [0x81, body.length]; |
| 15 | + return Buffer.concat([Buffer.from([tag, ...length]), body]); |
| 16 | +} |
| 17 | + |
| 18 | +(async () => { |
| 19 | + for (const [curve, oid] of [ |
| 20 | + ['p256', '06082a8648ce3d030107'], |
| 21 | + ['p384', '06052b81040022'], |
| 22 | + ['p521', '06052b81040023'], |
| 23 | + ]) { |
| 24 | + const privateKey = createPrivateKey(fixtures.readKey(`ec_${curve}_private.pem`)); |
| 25 | + const expected = privateKey.export({ type: 'pkcs8', format: 'der' }); |
| 26 | + const jwk = privateKey.export({ format: 'jwk' }); |
| 27 | + const curveOid = Buffer.from(oid, 'hex'); |
| 28 | + const algorithmIdentifier = der( |
| 29 | + 0x30, Buffer.from('06072a8648ce3d0201', 'hex'), curveOid); |
| 30 | + |
| 31 | + for (const includeParameters of [false, true]) { |
| 32 | + const ecPrivateKey = der( |
| 33 | + 0x30, Buffer.from('020101', 'hex'), der(0x04, Buffer.from(jwk.d, 'base64url')), |
| 34 | + includeParameters ? der(0xa0, curveOid) : Buffer.alloc(0)); |
| 35 | + const privateOnly = der( |
| 36 | + 0x30, Buffer.from('020100', 'hex'), algorithmIdentifier, der(0x04, ecPrivateKey)); |
| 37 | + for (const name of ['ECDSA', 'ECDH']) { |
| 38 | + const key = await subtle.importKey( |
| 39 | + 'pkcs8', privateOnly, { name, namedCurve: jwk.crv }, true, |
| 40 | + name === 'ECDSA' ? ['sign'] : ['deriveBits']); |
| 41 | + const original = KeyObject.from(key).export({ type: 'pkcs8', format: 'der' }); |
| 42 | + const actual = Buffer.from(await subtle.exportKey('pkcs8', key)); |
| 43 | + assert.deepStrictEqual(actual, expected); |
| 44 | + assert.deepStrictEqual( |
| 45 | + KeyObject.from(key).export({ type: 'pkcs8', format: 'der' }), original); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +})().then(common.mustCall()); |
0 commit comments