crypto-shim fixes vulnerable crypto-browserify package used by sheetjs/crypto, shim is based on crypto-js
52 lines
1.4 KiB
TypeScript
52 lines
1.4 KiB
TypeScript
import CryptoJS from 'crypto-js'
|
|
import { Buffer } from 'buffer'
|
|
|
|
class CryptoJSHash {
|
|
private hasher: any
|
|
|
|
constructor(algorithm: string) {
|
|
const algo = algorithm.toLowerCase()
|
|
switch (algo) {
|
|
case 'md5':
|
|
this.hasher = CryptoJS.algo.MD5.create()
|
|
break
|
|
case 'sha1':
|
|
this.hasher = CryptoJS.algo.SHA1.create()
|
|
break
|
|
case 'sha256':
|
|
this.hasher = CryptoJS.algo.SHA256.create()
|
|
break
|
|
case 'sha384':
|
|
this.hasher = CryptoJS.algo.SHA384.create()
|
|
break
|
|
case 'sha512':
|
|
this.hasher = CryptoJS.algo.SHA512.create()
|
|
break
|
|
case 'md2':
|
|
throw new Error('MD2 not supported - file uses very old encryption')
|
|
default:
|
|
throw new Error(`Hash algorithm ${algorithm} not supported`)
|
|
}
|
|
}
|
|
|
|
update(data: string | Buffer | Uint8Array) {
|
|
const wordArray =
|
|
typeof data === 'string'
|
|
? CryptoJS.enc.Utf8.parse(data)
|
|
: CryptoJS.lib.WordArray.create(data as any)
|
|
this.hasher.update(wordArray)
|
|
return this
|
|
}
|
|
|
|
digest(encoding?: 'hex' | 'base64' | 'buffer') {
|
|
const hash = this.hasher.finalize()
|
|
if (encoding === 'hex') return hash.toString(CryptoJS.enc.Hex)
|
|
if (encoding === 'base64') return hash.toString(CryptoJS.enc.Base64)
|
|
return Buffer.from(hash.toString(CryptoJS.enc.Hex), 'hex')
|
|
}
|
|
}
|
|
|
|
export const createHash = (algorithm: string) => new CryptoJSHash(algorithm)
|
|
|
|
export default { createHash }
|