Skip to content
Myr

crypto.ts

This file

Path

src/utils/crypto.ts

58 lines · 1.5 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–58why, one step back
1/**
2 * @module3 * Crypto utility.4 */56import type { JSONValue } from './types'78type Algorithm = {9 name: string10 alias: string11}1213type Data = string | boolean | number | JSONValue | ArrayBufferView | ArrayBuffer1415export const sha256 = async (data: Data): Promise<string | null> => {16 const algorithm: Algorithm = { name: 'SHA-256', alias: 'sha256' }17 const hash = await createHash(data, algorithm)18 return hash19}2021export const sha1 = async (data: Data): Promise<string | null> => {22 const algorithm: Algorithm = { name: 'SHA-1', alias: 'sha1' }23 const hash = await createHash(data, algorithm)24 return hash25}2627export const md5 = async (data: Data): Promise<string | null> => {28 const algorithm: Algorithm = { name: 'MD5', alias: 'md5' }29 const hash = await createHash(data, algorithm)30 return hash31}3233export const createHash = async (data: Data, algorithm: Algorithm): Promise<string | null> => {34 let sourceBuffer: ArrayBufferView | ArrayBuffer3536 if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) {37 sourceBuffer = data38 } else {39 if (typeof data === 'object') {40 data = JSON.stringify(data)41 }42 sourceBuffer = new TextEncoder().encode(String(data))43 }4445 if (crypto && crypto.subtle) {46 const buffer = await crypto.subtle.digest(47 {48 name: algorithm.name,49 },50 sourceBuffer as ArrayBuffer51 )52 const hash = Array.prototype.map53 .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))54 .join('')55 return hash56 }57 return null58}