Blog | G5 Cyber Security

Browser Javascript & Private Keys: Security Risks

TL;DR

Storing private keys directly in browser javascript is extremely insecure. It’s a very bad idea and should be avoided at all costs. This guide explains why, and what you should do instead.

Why it’s a Bad Idea

Javascript runs on the user’s computer, meaning anyone with access to their browser (or malicious software running on it) can potentially steal your keys. Here’s a breakdown of the risks:

What You Should Do Instead

Here are several much safer alternatives:

1. Use a Backend Server

  1. Store Keys on the Server: The most secure option is to store your private keys on a dedicated backend server that you control.
  2. API Access: Your Javascript code should communicate with this server via a secure API (HTTPS) to perform operations requiring the private key. Never expose the key directly to the client-side javascript.
  3. Example (Conceptual):
    // Client-Side Javascript
    fetch('/api/sign_message', {
      method: 'POST',
      body: JSON.stringify({ message: 'Your Message' }),
    }) 
    .then(response => response.json()) 
    .then(data => console.log(data.signature));
    
    // Server-Side (e.g., Node.js)
    app.post('/api/sign_message', (req, res) => {
      const message = req.body.message;
      const signature = signMessageWithPrivateKey(message);
      res.json({ signature });
    });

2. WebAuthn/Passkeys

WebAuthn allows users to authenticate using hardware security keys (like YubiKeys) or platform authenticators (fingerprint scanners, facial recognition). This avoids storing private keys in Javascript altogether.

3. Secure Enclaves (WebAssembly with WASM-based cryptography)

This is a more advanced option, but can provide client-side cryptographic operations without exposing keys directly.

4. Hardware Security Modules (HSMs)

Similar to backend servers, but using dedicated hardware for key storage and cryptographic operations.

Important Considerations

Exit mobile version