Encryption and decryption
Use RSA public key algorithms to encrypt and decrypt
This page is outdated. Please visit here to see the use case of Rust function in encryption and decryption.
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 pure Rust implementation of the RSA algorithm 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 here.
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 generatedRSAKeyPair
is serialized into a JSON string and returned to the JavaScript caller.The
encrypt()
function takes aRSAPublicKey
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 aRSAPrivateKey
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 Recrypt-as-a-Service 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.
Last updated