1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- const nodeCrypto = require('crypto')
- module.exports = {
- postgresMd5PasswordHash,
- randomBytes,
- deriveKey,
- sha256,
- hmacSha256,
- md5,
- }
- const webCrypto = nodeCrypto.webcrypto || globalThis.crypto
- const subtleCrypto = webCrypto.subtle
- const textEncoder = new TextEncoder()
- function randomBytes(length) {
- return webCrypto.getRandomValues(Buffer.alloc(length))
- }
- async function md5(string) {
- try {
- return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex')
- } catch (e) {
-
-
-
- const data = typeof string === 'string' ? textEncoder.encode(string) : string
- const hash = await subtleCrypto.digest('MD5', data)
- return Array.from(new Uint8Array(hash))
- .map((b) => b.toString(16).padStart(2, '0'))
- .join('')
- }
- }
- async function postgresMd5PasswordHash(user, password, salt) {
- var inner = await md5(password + user)
- var outer = await md5(Buffer.concat([Buffer.from(inner), salt]))
- return 'md5' + outer
- }
- async function sha256(text) {
- return await subtleCrypto.digest('SHA-256', text)
- }
- async function hmacSha256(keyBuffer, msg) {
- const key = await subtleCrypto.importKey('raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
- return await subtleCrypto.sign('HMAC', key, textEncoder.encode(msg))
- }
- async function deriveKey(password, salt, iterations) {
- const key = await subtleCrypto.importKey('raw', textEncoder.encode(password), 'PBKDF2', false, ['deriveBits'])
- const params = { name: 'PBKDF2', hash: 'SHA-256', salt: salt, iterations: iterations }
- return await subtleCrypto.deriveBits(params, key, 32 * 8, ['deriveBits'])
- }
|