38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import { SM3 } from 'gm-crypto'
|
|
|
|
// 验证是否为有效的 hex 字符串
|
|
const isValidHex = (hex: string): boolean => {
|
|
return /^[0-9a-fA-F]*$/.test(hex) && hex.length % 2 === 0
|
|
}
|
|
|
|
// ArrayBuffer 转 hex 字符串
|
|
const arrayBufferToHex = (buffer: ArrayBuffer): string => {
|
|
const bytes = new Uint8Array(buffer)
|
|
return Array.from(bytes).map(byte => byte.toString(16).padStart(2, '0')).join('')
|
|
}
|
|
|
|
// SM3 计算
|
|
export const sm3Digest = (message: string): string => {
|
|
try {
|
|
// 验证消息是否为有效的 hex 字符串
|
|
if (!isValidHex(message)) {
|
|
throw new Error('Invalid message: must be hex string')
|
|
}
|
|
|
|
console.log('Input hex message:', message)
|
|
|
|
// 直接使用 hex 字符串计算 SM3
|
|
const result = SM3.digest(message, 'hex')
|
|
console.log('SM3 result:', result)
|
|
|
|
// 处理返回结果
|
|
const hexResult = typeof result === 'string' ? result : arrayBufferToHex(result)
|
|
console.log('Hex result:', hexResult)
|
|
|
|
return hexResult
|
|
} catch (error) {
|
|
console.error('SM3 digest error:', error)
|
|
throw error
|
|
}
|
|
}
|