Skip to content
Myr

refactor: create `utils/crypto.ts` (#118)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent 4822077 · Browse files · 5 files+93 added−73 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+93 added−73 removed

  • tests:+26 added−27 removed
  • other:+67 added−46 removed

5 files+93 added−73 removed

modified:src/middleware/basic-auth/basic-auth.ts+2 added-1 removed
modified:src/utils/buffer.test.ts+1 added-27 removed
modified:src/utils/buffer.ts+2 added-45 removed
added:src/utils/crypto.test.ts+25 added
added:src/utils/crypto.ts+63 added
1type Algorithm = {2 name: string3 alias: string4}56type Data = string | object | boolean78export const sha256 = async (data: Data) => {9 const algorithm: Algorithm = { name: 'SHA-256', alias: 'sha256' }10 const hash = await createHash(data, algorithm)11 return hash12}1314export const sha1 = async (data: Data) => {15 const algorithm: Algorithm = { name: 'SHA-1', alias: 'sha1' }16 const hash = await createHash(data, algorithm)17 return hash18}1920export const createHash = async (data: Data, algorithm: Algorithm): Promise<string> => {21 if (crypto && crypto.subtle) {22 const buffer = await crypto.subtle.digest(23 {24 name: algorithm.name,25 },26 new TextEncoder().encode(String(data))27 )28 const hash = Array.prototype.map29 .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))30 .join('')31 return hash32 }3334 try {35 const crypto = require('crypto')36 const hash = crypto.createHash(algorithm.alias).update(data).digest('hex')37 return hash38 } catch (e) {39 console.error(`If you want to create hash ${algorithm.name}, polyfill "crypto" module.`)40 throw e41 }42}4344export const decodeBase64 = (str: string) => {45 try {46 const text = atob(str)47 const length = text.length48 const bytes = new Uint8Array(length)49 for (let i = 0; i < length; i++) {50 bytes[i] = text.charCodeAt(i)51 }52 const decoder = new TextDecoder()53 return decoder.decode(bytes)54 } catch {}5556 try {57 const { Buffer } = require('buffer')58 return Buffer.from(str, 'base64').toString()59 } catch (e) {60 console.error('If you want to do "decodeBase64", polyfill "buffer" module.')61 throw e62 }63}