Skip to content

Commit

Permalink
feat: add native hkdf (#1124)
Browse files Browse the repository at this point in the history
* feat: add native hkdf

* feat: import only needed to do hkdf

* feat: tweak digest and arguments
  • Loading branch information
koolii authored and balazsorban44 committed Feb 1, 2021
1 parent 2562b3c commit e26297b
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/lib/jwt.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import crypto from 'crypto'
import jose from 'jose'
import hkdf from 'futoin-hkdf'
import logger from './logger'

// Set default algorithm to use for auto-generated signing key
Expand Down Expand Up @@ -136,13 +136,32 @@ async function getToken (params) {
let DERIVED_SIGNING_KEY_WARNING = false
let DERIVED_ENCRYPTION_KEY_WARNING = false

// Do the better hkdf of Node.js one added in `v15.0.0` and Third Party one
function hkdf (secret, { byteLength, encryptionInfo, digest = 'sha256' }) {
if (crypto.hkdfSync) {
return Buffer.from(
crypto.hkdfSync(
digest,
secret,
Buffer.alloc(0),
encryptionInfo,
byteLength
)
)
}
return require('futoin-hkdf')(secret, byteLength, { info: encryptionInfo, hash: digest })
}

function getDerivedSigningKey (secret) {
if (!DERIVED_SIGNING_KEY_WARNING) {
logger.warn('JWT_AUTO_GENERATED_SIGNING_KEY')
DERIVED_SIGNING_KEY_WARNING = true
}

const buffer = hkdf(secret, 64, { info: 'NextAuth.js Generated Signing Key', hash: 'SHA-256' })
const buffer = hkdf(secret, {
byteLength: 64,
encryptionInfo: 'NextAuth.js Generated Signing Key'
})
const key = jose.JWK.asKey(buffer, { alg: DEFAULT_SIGNATURE_ALGORITHM, use: 'sig', kid: 'nextauth-auto-generated-signing-key' })
return key
}
Expand All @@ -153,7 +172,10 @@ function getDerivedEncryptionKey (secret) {
DERIVED_ENCRYPTION_KEY_WARNING = true
}

const buffer = hkdf(secret, 32, { info: 'NextAuth.js Generated Encryption Key', hash: 'SHA-256' })
const buffer = hkdf(secret, {
byteLength: 32,
encryptionInfo: 'NextAuth.js Generated Encryption Key'
})
const key = jose.JWK.asKey(buffer, { alg: DEFAULT_ENCRYPTION_ALGORITHM, use: 'enc', kid: 'nextauth-auto-generated-encryption-key' })
return key
}
Expand Down

0 comments on commit e26297b

Please sign in to comment.