添加 sm3 测试用例

This commit is contained in:
cheney
2026-04-15 18:02:28 +08:00
parent fe1f7c14b4
commit a7aef0f7dd
4 changed files with 155 additions and 7 deletions
+26 -7
View File
@@ -5,14 +5,33 @@ 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 => {
// 验证消息是否为有效的 hex 字符串
if (!isValidHex(message)) {
throw new Error('Invalid message: must be hex 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
}
// 直接使用 message 作为输入,gm-crypto 会自动处理
const result = SM3.digest(message)
return typeof result === 'string' ? result : Buffer.from(result).toString('hex')
}