There are many cryptography libraries available for use and my suggestion is when you are implementing a cryptography algorithm then don’t do it by yourself, instead use one of these libraries like OpenSSL, WolfSSL, PolarSSL etc.
The code which I am going to share would mostly build upon OpenSSL.
OpenSSL is a general purpose cryptography library that provides open source implementation of Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.
This library includes a wide variety of cryptography algorithms like RSA, ECC and Certificate signing requests, checksums, managing certificates and performing encryption/decryption. The library is written in C language but it also has wrappers available for many other languages.
The Mac Operating System already comes with an installation of OpenSSL, which you can upgrade by using HomeBrew or Ports but for the coding purpose, you can follow this link to compile and install OpenSSL:
If you are working on Windows, then you can follow this link to compile and install OpenSSL:
After you configure and build the library, you should always perform a make test to ensure the library performs as expected under its self-tests.