scottohara / tvmanager

PWA for tracking recorded, watched & upcoming TV shows
MIT License
3 stars 0 forks source link

WebCrypto to replace 3rd party md5 library #97

Open scottohara opened 3 years ago

scottohara commented 3 years ago

md5 is used to generate a checksum of the JSON sent (export) or received (import). It would be preferred if we could compute these checksums using a native browser API instead of relying on a 3rd party library.

UPDATE: 5-Jul-2023 - uuid.v4() has now been replaced with crypto.randomUUID() in https://github.com/scottohara/tvmanager/commit/df65c633d8dcf0216bbd75c574f507d2dd6ef2fe

(Issue can remain open to track the replacement of md5 with a native equivalent)

uuid is used to generate v4 UUIDs for all entities. It is possible to generate these in the browser as follows:

https://medium.com/teads-engineering/generating-uuids-at-scale-on-the-web-2877f529d2a2

> Generating a 128-bit (16 bytes) random number with the Crypto API is as simple as:

crypto.getRandomValues(new Uint8Array(16))

> To turn these random bytes into a RFC-compliant version 4 UUID, one needs to set the variant and version bits, and then convert the bytes to hexadecimal digits separated by dashes.

> Another possibility is to use the File API in combination with the URL.createObjectURL function to obtain a Blob URL containing a UUID. Support for URL.createObjectURL is similar to Crypto at 99.9%.

const url = URL.createObjectURL(new Blob())
url.substring(url.lastIndexOf('/') + 1)

> The File API does not specify which version of UUID should be used or how it should be generated. In practice, Chromium-based browsers (Chrome and Edge) and WebKit reuse their Crypto implementation to generate random bytes, and then set/clear bits to create a v4 UUID. Firefox calls OS-level functions when they exist (CoCreateGuid on Windows, CFUUIDCreate on macOS), and otherwise falls back to using Crypto like Chromium and WebKit.

> Finally, browsers implement Crypto.getRandomValues by relying on the OS either to provide random numbers directly or to gather entropy and then regularly feed it to a PRNG, making it cryptographically secure (CSPRNG).

scottohara commented 3 years ago

From https://deno.com/blog/v1.11#more-web-crypto-apis-supported:

"Additionally we have added support for the recently standardized crypto.randomUUID function. It allows you to generate UUID v4 as per RFC 4122. This feature is already in Node.js and will ship in Chrome/Edge 92 by the end of next month.

console.log("Random UUID:", crypto.randomUUID());

We aim to expand the Web Crypto APIs in the next release, Deno 1.12, scheduled for July 13th."

See also #11