import crypto from 'crypto' import { compressUuid } from './string.util' const ENCODER = 'base64' const REG_KEY = /^[0-9a-fA-F]{63,64}$/ export function isEncrypt(msg: string) { return !REG_KEY.test(msg) } export function aesEncrypt(text: string, password: string, iv: string) { var md5 = crypto.createHash('md5') const key = md5.update(password).digest('hex') let cipher = crypto.createCipheriv('aes-256-cbc', key, iv) let encrypted = cipher.update(text, 'utf8', ENCODER) encrypted += cipher.final(ENCODER) return encrypted } export function aesDecrypt(encryptedText: string, password: string, iv: string) { var md5 = crypto.createHash('md5') const key = md5.update(password).digest('hex') let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv) let decrypted = decipher.update(encryptedText, ENCODER, 'utf8') return decrypted + decipher.final('utf8') } 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 sha512(password: string, salt: string) { let hash = crypto.createHmac('sha512', salt) hash.update(password) let value = hash.digest('hex') return { salt: salt, passwordHash: value, } } export function sha3_256(str: string) { let hash = crypto.createHash('sha3-256') hash.update(str) return hash.digest('hex') } export function genRandomString(length: number) { return crypto .randomBytes(Math.ceil(length / 2)) .toString('hex') .slice(0, length) } export function uuid() { return crypto.randomUUID() } export function shortUuid() { let uid = uuid() return compressUuid(uid) } export function md5(content: string) { var md5 = crypto.createHash('md5') return md5.update(content).digest('hex') } export function sha1(content: string) { var md5 = crypto.createHash('sha1') return md5.update(content).digest('hex') }