Skip to content

Commit 531f757

Browse files
authored
Merge pull request #7 from Edgio/issue-6
update crypto helpers to work in browser-compatible ways
2 parents 72bc7f0 + 21a9af1 commit 531f757

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

lib/crypto.js

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
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

310
const 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)

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@edgio/ectoken",
3-
"version": "2.0.2",
3+
"version": "2.0.3",
44
"description": "JS implementation of Edgio token (ectoken)",
55
"main": "index.js",
66
"repository": {

0 commit comments

Comments
 (0)