How to use Libsodium in Java for cryptography
When you opt for an upgrade from RSA
Libsodium uses the elliptic curve 25519 for authenticate encryption. It can achieve the same cryptographic strength as a RSA-based system using a smaller key size.
Libsodium is written in C. In order to use it in Java, we have to use one of the Java Binding, wrapper libraries written by third parties.
I found libsodium-jni(for Android) and libsodium-jna to be the easiest to use.
How do these binding libraries work
All these binding libraries require you to import the original libsodium (native C) library before using the binding functions. This is because all these libraries do is call the native C library for you (so you don’t have to deal with calling the C code in Java.)
libsodium-jna provides a helpful chart in its README mapping the native C and java functions.

If you take a look at the first cryptoSecretBoxEasy
function from the chart. The binding library calls the crypto_secretbox_easy()
function from the native library, passing in the given parameters as arguments.


Same is true for other Java binding libraries, libsodium-jni has a file with the declaration of all the native methods. This is because to use C or C++ code in Android, you specifically declare the method you want to invoke from native function.


How to use these library
The README from libsodium-jna has provided straightforward sample code, so the following example will be done in Android libsodium-jni.
Follow the official libsodium guide to know which function to use.
First make sure you load the native library into the binding library.
NaCl.sodium();
Symmetric Encryption use the same key to encrypt and decrypt data
Generate a symmetric key using the Sodium.randombytes()
function. The key is essentially just a randomly generated 32 bytes of data.
Sender can encrypt the data using Sodium.crypto_secretbox_easy()
function.
Notice the function takes five parameters. One of them is nonce, a randomly generated 24 bytes of data. Nonce must be consistent in both encryption and decryption, so a convenient way to store this information is to append it to the front of the encrypted message.
Receiver can decrypt the data using Sodium.crypto_secretbox_open_easy
function. The receiver can get the nonce (first 24 bytes) from the encrypted message.
Asymmetric Encryption always use this party’s secret key and the other party’s public key to encrypt and decrypt data
Both parties will generate their own set of public key and secret key pair.
You can generate public key from secret key using Sodium.crypto_scalarmult_base()
The sender can encrypt the data using Sodium.crypto_box_easy()
The receiver can decrypt the data using Sodium.crypto_box_open_easy()
You can encapsulate these functions into its own class
A good way to demonstrate how to use these functions is to write a unit test for them.
