75 lines
1.6 KiB
TypeScript
75 lines
1.6 KiB
TypeScript
import crypto from 'crypto'
|
|
|
|
export function hmac(input, key, out) {
|
|
return out
|
|
? crypto.createHmac('sha1', key).update(input).digest(out)
|
|
: crypto.createHmac('sha1', key).update(input).digest('hex')
|
|
}
|
|
|
|
export function genRandomString(length) {
|
|
return crypto
|
|
.randomBytes(Math.ceil(length / 2))
|
|
.toString('hex')
|
|
.slice(0, length)
|
|
}
|
|
|
|
export function sha512(password, salt) {
|
|
let hash = crypto.createHmac('sha512', salt)
|
|
hash.update(password)
|
|
let value = hash.digest('hex')
|
|
return {
|
|
salt: salt,
|
|
passwordHash: value,
|
|
}
|
|
}
|
|
|
|
export function sha1(str) {
|
|
const md5sum = crypto.createHash('sha1')
|
|
md5sum.update(str)
|
|
str = md5sum.digest('hex')
|
|
return str
|
|
}
|
|
|
|
export function hmacSha256(text: string, secret: string) {
|
|
const mac = crypto.createHmac('sha256', secret)
|
|
const data = mac.update(text).digest('hex').toLowerCase()
|
|
console.log(`HmacSHA256 rawContent is [${text}], key is [${secret}], hash result is [${data}]`)
|
|
return data
|
|
}
|
|
|
|
export function md5(str) {
|
|
const md5sum = crypto.createHash('md5')
|
|
md5sum.update(str)
|
|
str = md5sum.digest('hex')
|
|
return str
|
|
}
|
|
|
|
export function createSign(secretKey, paramStr, timestamp) {
|
|
paramStr = `${paramStr}:${timestamp}:${secretKey}`
|
|
return sha1(paramStr)
|
|
}
|
|
|
|
export function checkSign({
|
|
secretKey,
|
|
data,
|
|
sign,
|
|
signKeys,
|
|
}: {
|
|
secretKey: string
|
|
data: {}
|
|
sign: string
|
|
signKeys: string[]
|
|
}) {
|
|
signKeys.sort()
|
|
let signStr = ''
|
|
for (let key of signKeys) {
|
|
if (signStr.length > 0) {
|
|
signStr += '&'
|
|
}
|
|
signStr += `${key}=${data[key]}`
|
|
}
|
|
console.log(signStr)
|
|
let sign1 = hmacSha256(signStr, secretKey)
|
|
return sign1 === sign
|
|
}
|