Encryption and decryption
Use RSA public key algorithms to encrypt and decrypt
Last updated
Was this helpful?
Use RSA public key algorithms to encrypt and decrypt
Last updated
Was this helpful?
One of the frequently performed computing tasks is public key encryption and decryption. Rust and C++ code vastly outperforms JavaScript code in these tasks. In this tutorial, let's use as an example to show how to perform public key encryption and decryption in a Node.js web service.
The example project source code is .
The following Rust functions perform the encryption and decryption tasks.
The generate_key_pair()
function creates a random public / private key pair of specified length. The generated RSAKeyPair
is serialized into a JSON string and returned to the JavaScript caller.
The encrypt()
function takes a RSAPublicKey
in serialized JSON format, and a byte array message. It encrypts the message and returns the result as a byte array.
The decrypt()
function takes a RSAPrivateKey
in serialized JSON format, and an encrypted byte array message. It decrypts the message and returns the result as a byte array.
The Javascript host application calls the Rust functions as follows. It first calls the Rust generate_key_pair()
function to generate the key pair, and then saves the generated public and private keys respectively. It then uses the public key to encrypt a string message, and then use the private key to decrypt that message. The keys are serialized into JSON strings before passing to the Rust functions.
The RSA example is simple but provides substantial performance benefits when you run many public key encryption and decryption operations.
For a more complex example of public key encryption and decryption, please see our repo. It is a scalable approach for individuals to control access to private data without shared secrets or storing secrets (e.g., private keys) on a centralized service. As a part of the workflow, the web service needs to perform large amounts of proxy encryption using public keys. Rust and WebAssembly are ideally suited for this.