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
+ }
2
9
3
10
const iv_size_bytes = 12
4
11
@@ -44,7 +51,13 @@ async function encrypt(key, token, verbose = false) {
44
51
console . log ( '+---------------------------------------------------------------------------------------------------' )
45
52
}
46
53
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
48
61
}
49
62
50
63
/**
@@ -58,7 +71,9 @@ async function decrypt(key, token, verbose = false) {
58
71
const key_encoded = new TextEncoder ( ) . encode ( key )
59
72
const key_digest = await crypto . subtle . digest ( 'SHA-256' , key_encoded )
60
73
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' )
62
77
63
78
// First n bytes (iv_size_bytes) is the iv.
64
79
const iv = decoded_token . subarray ( 0 , iv_size_bytes )
0 commit comments