utils-webcrypto.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. const nodeCrypto = require('crypto')
  2. module.exports = {
  3. postgresMd5PasswordHash,
  4. randomBytes,
  5. deriveKey,
  6. sha256,
  7. hashByName,
  8. hmacSha256,
  9. md5,
  10. }
  11. /**
  12. * The Web Crypto API - grabbed from the Node.js library or the global
  13. * @type Crypto
  14. */
  15. // eslint-disable-next-line no-undef
  16. const webCrypto = nodeCrypto.webcrypto || globalThis.crypto
  17. /**
  18. * The SubtleCrypto API for low level crypto operations.
  19. * @type SubtleCrypto
  20. */
  21. const subtleCrypto = webCrypto.subtle
  22. const textEncoder = new TextEncoder()
  23. /**
  24. *
  25. * @param {*} length
  26. * @returns
  27. */
  28. function randomBytes(length) {
  29. return webCrypto.getRandomValues(Buffer.alloc(length))
  30. }
  31. async function md5(string) {
  32. try {
  33. return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
  34. } catch (e) {
  35. // `createHash()` failed so we are probably not in Node.js, use the WebCrypto API instead.
  36. // Note that the MD5 algorithm on WebCrypto is not available in Node.js.
  37. // This is why we cannot just use WebCrypto in all environments.
  38. const data = typeof string === 'string' ? textEncoder.encode(string) : string
  39. const hash = await subtleCrypto.digest('MD5', data)
  40. return Array.from(new Uint8Array(hash))
  41. .map((b) => b.toString(16).padStart(2, '0'))
  42. .join('')
  43. }
  44. }
  45. // See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html
  46. async function postgresMd5PasswordHash(user, password, salt) {
  47. const inner = await md5(password + user)
  48. const outer = await md5(Buffer.concat([Buffer.from(inner), salt]))
  49. return 'md5' + outer
  50. }
  51. /**
  52. * Create a SHA-256 digest of the given data
  53. * @param {Buffer} data
  54. */
  55. async function sha256(text) {
  56. return await subtleCrypto.digest('SHA-256', text)
  57. }
  58. async function hashByName(hashName, text) {
  59. return await subtleCrypto.digest(hashName, text)
  60. }
  61. /**
  62. * Sign the message with the given key
  63. * @param {ArrayBuffer} keyBuffer
  64. * @param {string} msg
  65. */
  66. async function hmacSha256(keyBuffer, msg) {
  67. const key = await subtleCrypto.importKey('raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
  68. return await subtleCrypto.sign('HMAC', key, textEncoder.encode(msg))
  69. }
  70. /**
  71. * Derive a key from the password and salt
  72. * @param {string} password
  73. * @param {Uint8Array} salt
  74. * @param {number} iterations
  75. */
  76. async function deriveKey(password, salt, iterations) {
  77. const key = await subtleCrypto.importKey('raw', textEncoder.encode(password), 'PBKDF2', false, ['deriveBits'])
  78. const params = { name: 'PBKDF2', hash: 'SHA-256', salt: salt, iterations: iterations }
  79. return await subtleCrypto.deriveBits(params, key, 32 * 8, ['deriveBits'])
  80. }