Encrypted redirects and the Web Crypto API
Following up from last week's article about building your own url shortener, this week we'll tackle password-protected redirects. The simplest way that came to my mind to solve this problem is to generate the redirection page as usual but to save the redirection target as a password-encrypted string. Once the user provides the password via some means (e.g. a simple client-side form), they get redirected to the target URL. If the password is wrong a generic error message is displayed. The necessary cryptographic functions are provided by the Web Crypto Api. For this to work your shortener must be hosted in a secure context (HTTPS).
Now, I'm not a cryptographer (and it might show), so I got a lot of inspiration from restic, which is an audited backup solution. The idea is simple:
- Derive master-key
k1from a password
pusing a key-derivation function (
CryptoKey-Format, which is used by Web Crypto.
- Derive a key
k2for use in AES-GCM from
k1, using random 16-byte salt
s. Use the Web Crypto CSPRNG.
- Get a random 12-Byte nonce
ivusing the Web Crypto CSPRNG.
- Get cyphertext
ctby encrypting the URL
urlusing AES-GCM together with
- Write a base64 encoded Byte Array consisting of [
ct] into the source of the redirection page. This is called
- Publish the redirection page.
- Once the user visits the redirection page, he gets prompted for
phe can get
b64), he can get
b64), he can use AES-GCM to decrypt
b64) to finally get
- Redirect him to
Of course, the user needs to share
p out-of-band somehow, but that is left to the imagination of the host.
Base64-Conversions are not done using the native btoa or atob function, due to the Unicode Problem.
I really enjoy adding a couple of features to
krz-re. It has proven useful not only for citations, as discussed last time but also as a way to securely share links with friends.