Skip to content

Instantly share code, notes, and snippets.

@dtarnawsky
Last active November 23, 2022 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtarnawsky/a2effb687a7f97d04c422da96df3fcd7 to your computer and use it in GitHub Desktop.
Save dtarnawsky/a2effb687a7f97d04c422da96df3fcd7 to your computer and use it in GitHub Desktop.
Method to encrypt data on the web (backend knows private key and can decrypt)

Encrypting on the web

The web crypto API provides an encryption algorithm called RSA-OAEP which is suitable for encrypting data on the web.

Link for the Web Crypto API:

https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt

Compatibility

This is widely available (link) : eg Safari for iOS v7, Webview Android 37, Safari 7, Chrome 37, Node 15, Deno 1.18

The RSA-OAEP algorithm is a public key encryption system (link).

This means that you will encrypt data with a public key and decrypt data with a private key.

The backend will generate a key storing the public and private keys and sending the public key to the client (web browser or web native).

The web application can store the public key and use it for encryption of sensitive information such as username/password, API payloads etc.

The encrypted payloads can be sent to the backend API which can decrypt them using the private key.

Sample code

Working example found here. View dev tools for the javascript code to copy (from the RSA-OAEP file)

Caveats

As data encrypted using this method cannot be decrypted on the client it is not suitable for persisting data to a device, but it is useful in encrypting data entered by the user which will be passed to your backend as it means that if memory is dumped whilst the data is in transit it cannot be decrypted without the private key which only the backend knows.

The encrypt method is only available in a secure context (HTTPS).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment