z-utils-ts
Version:
使用TypeScript编写的工具函数库
29 lines (26 loc) • 843 B
text/typescript
export async function computeSHA256Hash(data: string) {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest("SHA-256", dataBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
let len = hashArray.length
let result = "";
for(let i = 0; i < len; i++) {
hashArray[i] = hashArray[i] & 0xFF;
let byte = hashArray[i];
result += padStart(byte.toString(16), 2)
}
return result;
}
function padStart(num: string, length: number, symbol: string = '0'): string {
while (num.length < length) {
num = symbol + num;
}
return num;
}
// function padEnd(num: string, length: number, symbol: string = '0'): string {
// while (num.length < length) {
// num = num + symbol;
// }
// return num;
// }