diff --git a/lib/help/key_utils.js b/lib/help/key_utils.js index a3013eacdc..dc3556b976 100644 --- a/lib/help/key_utils.js +++ b/lib/help/key_utils.js @@ -21,8 +21,6 @@ const crvToOidBuf = new Map([ ['P-521', Buffer.from('06052b81040023', 'hex')] ]) -const formatPem = (base64pem, descriptor) => `-----BEGIN ${descriptor} KEY-----\n${base64pem.match(/.{1,64}/g).join('\n')}\n-----END ${descriptor} KEY-----` - const keyObjectToJWK = { rsa: { private (keyObject) { @@ -128,7 +126,7 @@ const jwkToPem = { private (jwk) { const RSAPrivateKey = asn1.get('RSAPrivateKey') - const b64 = RSAPrivateKey.encode({ + return RSAPrivateKey.encode({ version: 0, n: base64url.decodeToBuffer(jwk.n), e: base64url.decodeToBuffer(jwk.e), @@ -138,27 +136,23 @@ const jwkToPem = { dp: base64url.decodeToBuffer(jwk.dp), dq: base64url.decodeToBuffer(jwk.dq), qi: base64url.decodeToBuffer(jwk.qi) - }, 'der').toString('base64') - - return formatPem(b64, 'RSA PRIVATE') + }, 'pem', { label: 'RSA PRIVATE KEY' }).toString('base64') }, public (jwk) { const RSAPublicKey = asn1.get('RSAPublicKey') - const b64 = RSAPublicKey.encode({ + return RSAPublicKey.encode({ version: 0, n: base64url.decodeToBuffer(jwk.n), e: base64url.decodeToBuffer(jwk.e) - }, 'der').toString('base64') - - return formatPem(b64, 'RSA PUBLIC') + }, 'pem', { label: 'RSA PUBLIC KEY' }).toString('base64') } }, EC: { private (jwk) { const ECPrivateKey = asn1.get('ECPrivateKey') - const b64 = ECPrivateKey.encode({ + return ECPrivateKey.encode({ version: 0, privateKey: base64url.decodeToBuffer(jwk.d), parameters: { @@ -166,22 +160,18 @@ const jwkToPem = { value: crvToOid.get(jwk.crv) }, publicKey: concatEcPublicKey(jwk.x, jwk.y) - }, 'der').toString('base64') - - return formatPem(b64, 'EC PRIVATE') + }, 'pem', { label: 'EC PRIVATE KEY' }).toString('base64') }, public (jwk) { const PublicKeyInfo = asn1.get('PublicKeyInfo') - const b64 = PublicKeyInfo.encode({ + return PublicKeyInfo.encode({ algorithm: { algorithm: EC_KEY_OID, parameters: crvToOidBuf.get(jwk.crv) }, publicKey: concatEcPublicKey(jwk.x, jwk.y) - }, 'der').toString('base64') - - return formatPem(b64, 'PUBLIC') + }, 'pem', { label: 'PUBLIC KEY' }).toString('base64') } } }