Skip to content

Commit

Permalink
refactor: use pem from asn1.js
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Mar 26, 2019
1 parent 12357f8 commit c5c985b
Showing 1 changed file with 8 additions and 18 deletions.
26 changes: 8 additions & 18 deletions lib/help/key_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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),
Expand All @@ -138,50 +136,42 @@ 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: {
type: 'namedCurve',
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')
}
}
}
Expand Down

0 comments on commit c5c985b

Please sign in to comment.