Skip to content

Commit

Permalink
Merge pull request #7 from Edgio/issue-6
Browse files Browse the repository at this point in the history
update crypto helpers to work in browser-compatible ways
  • Loading branch information
tmountjr authored Jul 31, 2024
2 parents 72bc7f0 + 21a9af1 commit 531f757
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@edgio/ectoken",
"version": "2.0.2",
"version": "2.0.3",
"description": "JS implementation of Edgio token (ectoken)",
"main": "index.js",
"repository": {
Expand Down

0 comments on commit 531f757

Please sign in to comment.