node-postgres/packages/pg/lib/crypto/utils-legacy.js
Pete Bacon Darwin 5532ca51db Use WebCrypto APIs where possible
The only place we are stuck with node's original crypto API
is for generating md5 hashes, which are not supported by WebCrypto.
2023-05-15 07:29:07 +01:00

38 lines
1022 B
JavaScript

'use strict'
// This file contains crypto utility functions for versions of Node.js < 15.0.0,
// which does not support the WebCrypto.subtle API.
const nodeCrypto = require('crypto')
function md5(string) {
return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
}
// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
function postgresMd5PasswordHash(user, password, salt) {
var inner = md5(password + user)
var outer = md5(Buffer.concat([Buffer.from(inner), salt]))
return 'md5' + outer
}
function sha256(text) {
return nodeCrypto.createHash('sha256').update(text).digest()
}
function hmacSha256(key, msg) {
return nodeCrypto.createHmac('sha256', key).update(msg).digest()
}
async function deriveKey(password, salt, iterations) {
return nodeCrypto.pbkdf2Sync(password, salt, iterations, 32, 'sha256')
}
module.exports = {
postgresMd5PasswordHash,
randomBytes: nodeCrypto.randomBytes,
deriveKey,
sha256,
hmacSha256,
md5,
}