Secure R REST API with libsodium and RestRserve

Ferry Djaja
2 min readOct 12, 2020

This tutorial will walkthrough how to secure R REST API with Sodium using RestRserve framework.

Sodium

As mentioned in https://doc.libsodium.org, Sodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more.

The sodium R package provides bindings to libsodium, https://cran.r-project.org/web/packages/sodium/vignettes/intro.html.

RestRserve

RestRserve is an R web API framework for building high-performance and robust microservices and app backends.

API Key Generator Logic

We will create a table in database to store the keys and phrases. With this we can use multiple keys and phrases. We can also add a flag in the table to indicate whether the key is active or inactive.

The key and phrase will be an input and it will be fed to R script with Sodium library to generate the chiper with the random nonce.

Decryption Process

Decryption process is very simple. Inputs are random chiper, nonce and key. And the output will be phrase. If the phrase is valid with the one we stored in database, then we execute the main program and return the result back to the client.

Code Implementation

Here is a simple implementation in R Script.

Using Postman

Using Postman, you can fill in the required params and performs the POST request to get the result. Test using the invalid id and key and see if you still can get the result.

Conclusion

Hope this simple trick can add more steps to secure your API with Sodium and RestRserve. As an alternate to RestRServe, you can also use Plumber.

Do let me know if you have any comments.

--

--