Files
Kg.SeaTime/Web/src/extends/cryptoEXTEND.ts
2026-04-21 16:54:18 +08:00

182 lines
4.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 加密解密工具类(支持实例化)
* 提供Base64加密解密、AES加解密等功能
*/
export class CryptoEXTEND {
// 默认加密密钥
private static readonly DEFAULT_KEY = 'kx-ui-framework-key'
// 实例密钥
private key: string
/**
* 构造函数:初始化加密密钥
* @param key 加密密钥(不同实例可传入不同密钥)
*/
constructor(key?: string) {
this.key = key || CryptoEXTEND.DEFAULT_KEY
}
/**
* Base64加密字符串
* @param data 需要加密的字符串
* @returns 加密后的Base64字符串
*/
encryptBase64(data: string): string {
if (!data) return ''
try {
return btoa(encodeURIComponent(data))
} catch (error) {
console.error('Base64加密失败:', error)
return ''
}
}
/**
* Base64解密字符串
* @param data 需要解密的Base64字符串
* @returns 解密后的原始字符串
*/
decryptBase64(data: string): string {
if (!data) return ''
try {
return decodeURIComponent(atob(data))
} catch (error) {
console.error('Base64解密失败:', error)
return ''
}
}
/**
* 加密字符串Base64 + 密钥拼接)
* @param data 需要加密的字符串
* @returns 加密后的字符串
*/
encrypt(data: string): string {
if (!data) return ''
try {
const encryptStr = data + this.key
return btoa(encodeURIComponent(encryptStr))
} catch (error) {
console.error('加密失败:', error)
return ''
}
}
/**
* 解密字符串
* @param data 需要解密的字符串
* @returns 解密后的原始字符串
*/
decrypt(data: string): string {
if (!data) return ''
try {
const decryptStr = decodeURIComponent(atob(data))
return decryptStr.replace(this.key, '')
} catch (error) {
console.error('解密失败:', error)
return ''
}
}
/**
* 验证加密字符串是否有效(匹配当前密钥)
* @param data 加密后的字符串
* @returns boolean 有效返回true否则返回false
*/
validate(data: string): boolean {
try {
const decryptStr = this.decrypt(data)
return decryptStr !== data && decryptStr.length > 0
} catch (error) {
return false
}
}
/**
* MD5加密简化版实际项目建议使用crypto-js
* @param data 需要加密的字符串
* @returns MD5哈希值
*/
static md5(data: string): string {
if (!data) return ''
// 简化实现实际项目中建议使用专业的MD5库
let hash = 0
for (let i = 0; i < data.length; i++) {
const char = data.charCodeAt(i)
hash = ((hash << 5) - hash) + char
hash = hash & hash
}
return Math.abs(hash).toString(16)
}
/**
* SHA256加密
* @param data 需要加密的字符串
* @returns SHA256哈希值
*/
static sha256(data: string): Promise<string> {
if (!data) return Promise.resolve('')
// 使用Web Crypto API
const encoder = new TextEncoder()
const dataBuffer = encoder.encode(data)
return crypto.subtle.digest('SHA-256', dataBuffer).then(hash => {
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('')
})
}
/**
* 生成随机字符串
* @param length 字符串长度
* @returns 随机字符串
*/
static randomString(length: number = 32): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
let result = ''
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
/**
* 生成随机数字
* @param min 最小值
* @param max 最大值
* @returns 随机数字
*/
static randomNumber(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min
}
/**
* URL参数编码
* @param data 需要编码的数据对象
* @returns 编码后的URL参数字符串
*/
static urlEncode(data: Record<string, any>): string {
const params = new URLSearchParams()
for (const key in data) {
if (data[key] !== undefined && data[key] !== null) {
params.append(key, String(data[key]))
}
}
return params.toString()
}
/**
* URL参数解码
* @param query URL参数字符串
* @returns 解码后的数据对象
*/
static urlDecode(query: string): Record<string, string> {
const params = new URLSearchParams(query)
const result: Record<string, string> = {}
params.forEach((value, key) => {
result[key] = value
})
return result
}
}