Skip to content
Myr

fix(utils/crypto): make Binary and JSON object crypto correct (#454)

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 5838f9d · Browse files · 6 files+89 added−10 removed
This commit

State

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

Diff stats

6 files+89 added−10 removed

  • tests:+57 added−2 removed
  • other:+32 added−8 removed

6 files+89 added−10 removed

modified:deno_dist/utils/body.ts+3 added-2 removed
modified:deno_dist/utils/crypto.ts+13 added-2 removed
modified:src/middleware/etag/index.test.ts+41 added-1 removed
modified:src/utils/body.ts+3 added-2 removed
modified:src/utils/crypto.test.ts+16 added-1 removed
1import { createHash } from 'crypto'2import { sha256, sha1, md5 } from './crypto'34describe('crypto', () => {5 it('sha256', async () => {
10 unmodified lines
16 expect(await sha1('hono')).toBe('28c7e86f5732391917876b45c06c626c04d77f39')17 expect(await sha1('炎')).toBe('d56e09ae2421b2b8a0b5ee5fdceaed663c8c9472')18 expect(await sha1('abcdedf')).not.toBe('abcdef')19 })19 2021 it('md5', async () => {22 expect(await md5('hono')).toBe('cf22a160789a91dd5f737cd3b2640cc2')23 expect(await md5('炎')).toBe('f620d89a5a782c22b4420acb39121be3')24 expect(await md5('abcdedf')).not.toBe('abcdef')25 })2627 it('Should not be the same values - compare difference objects', async () => {28 expect(await sha256({ foo: 'bar' })).not.toEqual(29 await sha256({30 bar: 'foo',31 })32 )33 })3435 it('Should create hash for Buffer', async () => {36 const hash = createHash('sha256').update(new Uint8Array(1)).digest('hex')37 expect(await sha256(new Uint8Array(1))).toBe(hash)38 expect(await sha256(new Uint8Array(1))).not.toEqual(await sha256(new Uint8Array(2)))39 })40})
modified:src/utils/crypto.ts+13 added-2 removed
1 unmodified line
2 name: string3 alias: string4}56type Data = string | object | boolean6type Data = string | boolean | number | object | ArrayBufferView | ArrayBuffer78export const sha256 = async (data: Data) => {9 const algorithm: Algorithm = { name: 'SHA-256', alias: 'sha256' }10 const hash = await createHash(data, algorithm)
12 unmodified lines
23 return hash24}2526export const createHash = async (data: Data, algorithm: Algorithm): Promise<string | null> => {27 let sourceBuffer: ArrayBufferView | ArrayBuffer2829 if (ArrayBuffer.isView(data) || data instanceof ArrayBuffer) {30 sourceBuffer = data31 } else {32 if (typeof data === 'object') {33 data = JSON.stringify(data)34 }35 sourceBuffer = new TextEncoder().encode(String(data))36 }3738 if (crypto && crypto.subtle) {39 const buffer = await crypto.subtle.digest(40 {41 name: algorithm.name,42 },32 new TextEncoder().encode(String(data))43 sourceBuffer44 )45 const hash = Array.prototype.map46 .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))47 .join('')
4 unmodified lines