Skip to content

Commit

Permalink
update crypto helpers to work in browser-compatible ways
Browse files Browse the repository at this point in the history
  • Loading branch information
tmountjr committed Jul 31, 2024
1 parent 72bc7f0 commit 3bdc03d
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/crypto.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
const crypto = require('crypto')
let crypto
if (typeof window !== 'undefined' && window.crypto) {
// Use the Web API if it's available.
crypto = window.crypto
} else {
// Otherwise use Node.js's version
crypto = require('crypto')
}

const iv_size_bytes = 12

Expand Down Expand Up @@ -44,7 +51,13 @@ async function encrypt(key, token, verbose = false) {
console.log('+---------------------------------------------------------------------------------------------------')
}

return Buffer.from(iv_ciphertext).toString('base64url')
// Convert non-url-safe base64 string to url-safe version in a way that browsers
// won't complain about.
const toReturn = Buffer.from(iv_ciphertext).toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '')
return toReturn
}

/**
Expand All @@ -58,7 +71,9 @@ async function decrypt(key, token, verbose = false) {
const key_encoded = new TextEncoder().encode(key)
const key_digest = await crypto.subtle.digest('SHA-256', key_encoded)

const decoded_token = Buffer.from(token, 'base64url')
// Convert url-safe base64 string to its standard base64 counterpart in a way
// that browsers won't complain about.
const decoded_token = Buffer.from(token.replace(/-/g, '+').replace(/_/g, '/'), 'base64')

// First n bytes (iv_size_bytes) is the iv.
const iv = decoded_token.subarray(0, iv_size_bytes)
Expand Down

0 comments on commit 3bdc03d

Please sign in to comment.