Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update crypto helpers to work in browser-compatible ways #7

Merged
merged 2 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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