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 passwordpusing a key-derivation function (PBKDF2) inCryptoKey-Format, which is used by Web Crypto. - Derive a key
k2for use in AES-GCM fromk1, using random 16-byte salts. Use the Web Crypto CSPRNG. - Get a random 12-Byte nonce
ivusing the Web Crypto CSPRNG. - Get cyphertext
ctby encrypting the URLurlusing AES-GCM together withivandk2. - Write a base64 encoded Byte Array consisting of [
iv,salt,ct] into the source of the redirection page. This is calledb64. - Publish the redirection page.
- Once the user visits the redirection page, he gets prompted for
p. - Using
phe can getk1. - Using
k1ands(gotten fromb64), he can getk2. - Using
k2andiv(fromb64), he can use AES-GCM to decryptct(fromb64) to finally geturl. - Redirect him to
url.
You can look at the actual implementation in the repository for krz-re. And a deployed example, redirecting to another article on this blog, here. The password is "password1234".
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.
Conclusion
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.