utils-legacy.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict'
  2. // This file contains crypto utility functions for versions of Node.js < 15.0.0,
  3. // which does not support the WebCrypto.subtle API.
  4. const nodeCrypto = require('crypto')
  5. function md5(string) {
  6. return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
  7. }
  8. // See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
  9. function postgresMd5PasswordHash(user, password, salt) {
  10. const inner = md5(password + user)
  11. const outer = md5(Buffer.concat([Buffer.from(inner), salt]))
  12. return 'md5' + outer
  13. }
  14. function sha256(text) {
  15. return nodeCrypto.createHash('sha256').update(text).digest()
  16. }
  17. function hashByName(hashName, text) {
  18. hashName = hashName.replace(/(\D)-/, '$1') // e.g. SHA-256 -> SHA256
  19. return nodeCrypto.createHash(hashName).update(text).digest()
  20. }
  21. function hmacSha256(key, msg) {
  22. return nodeCrypto.createHmac('sha256', key).update(msg).digest()
  23. }
  24. async function deriveKey(password, salt, iterations) {
  25. return nodeCrypto.pbkdf2Sync(password, salt, iterations, 32, 'sha256')
  26. }
  27. module.exports = {
  28. postgresMd5PasswordHash,
  29. randomBytes: nodeCrypto.randomBytes,
  30. deriveKey,
  31. sha256,
  32. hashByName,
  33. hmacSha256,
  34. md5,
  35. }