1- const crypto = require ( 'crypto' )
1+ let crypto
2+ if ( typeof window !== 'undefined' && window . crypto ) {
3+ // Use the Web API if it's available.
4+ crypto = window . crypto
5+ } else {
6+ // Otherwise use Node.js's version
7+ crypto = require ( 'crypto' )
8+ }
29
310const iv_size_bytes = 12
411
@@ -44,7 +51,13 @@ async function encrypt(key, token, verbose = false) {
4451 console . log ( '+---------------------------------------------------------------------------------------------------' )
4552 }
4653
47- return Buffer . from ( iv_ciphertext ) . toString ( 'base64url' )
54+ // Convert non-url-safe base64 string to url-safe version in a way that browsers
55+ // won't complain about.
56+ const toReturn = Buffer . from ( iv_ciphertext ) . toString ( 'base64' )
57+ . replace ( / \+ / g, '-' )
58+ . replace ( / \/ / g, '_' )
59+ . replace ( / = + $ / , '' )
60+ return toReturn
4861}
4962
5063/**
@@ -58,7 +71,9 @@ async function decrypt(key, token, verbose = false) {
5871 const key_encoded = new TextEncoder ( ) . encode ( key )
5972 const key_digest = await crypto . subtle . digest ( 'SHA-256' , key_encoded )
6073
61- const decoded_token = Buffer . from ( token , 'base64url' )
74+ // Convert url-safe base64 string to its standard base64 counterpart in a way
75+ // that browsers won't complain about.
76+ const decoded_token = Buffer . from ( token . replace ( / - / g, '+' ) . replace ( / _ / g, '/' ) , 'base64' )
6277
6378 // First n bytes (iv_size_bytes) is the iv.
6479 const iv = decoded_token . subarray ( 0 , iv_size_bytes )
0 commit comments