I develop a website and I need to store a private key on the client side. How to securely store this variable on the client side? Can I use sessionStorage?
(I would like this (variable) information to be accessible only to the current user. As soon as he closes his browser, the data will have to be deleted.)
Thank you.
At a top level, yes, sessionStorage
will do what you need. To quote MDN’s page on sessionStorage
:
- A page session lasts as long as the browser is open, and survives over page reloads and restores.
- Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
- Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
- Closing a tab/window ends the session and clears objects in sessionStorage.
There are several things to be careful of though. Firstly, any connection to the server would need to be done securely. This necessitates an HTTPS connection, probably with TLS 1.2 or 1.3 at this point.
Secondly, you’ll need to make sure that the page environment is clean. This means that you can’t load 3rd party JavaScript that could exfiltrate the private key. At an absolute minimum, any third party JS you load will need to be audited first and then have an integrity
attribute added to make sure it doesn’t change.
Finally, you probably would want to add something to destroy the key after the user has finished using the page. This could be warning them to close the page after they’ve finished using the system, or something more automatic like retiring the key after x minutes and getting the system to negotiate a new one in time. Obviously there’s a balance here between security and usability, but the best systems can do this in a user-transparent way.