General code optmisations and cleanup. (#15)

Updated `version_compare` based on this issue: #13 
Got rid of `replace_string_contents` helper func.
Replaced #define macros with static consts.
Moved comments from headers to source files.
This commit is contained in:
Ravin Perera
2019-10-10 12:57:46 +05:30
committed by GitHub
parent 374424f98f
commit d8581f7ce9
12 changed files with 331 additions and 299 deletions

View File

@@ -9,6 +9,10 @@ using namespace std;
namespace crypto
{
/**
* Initializes the crypto subsystem. Must be called once during application startup.
* @return 0 for successful initialization. -1 for failure.
*/
int init()
{
if (sodium_init() < 0)
@@ -20,6 +24,9 @@ int init()
return 0;
}
/**
* Generates a signing key pair using libsodium and assigns them to the provided strings.
*/
void generate_signing_keys(string &pubkey, string &seckey)
{
//Generate key pair using libsodium default algorithm. (Currently using ed25519)
@@ -28,10 +35,17 @@ void generate_signing_keys(string &pubkey, string &seckey)
unsigned char seckeychars[crypto_sign_SECRETKEYBYTES];
crypto_sign_keypair(pubkeychars, seckeychars);
util::replace_string_contents(pubkey, (char *)pubkeychars, crypto_sign_PUBLICKEYBYTES);
util::replace_string_contents(seckey, (char *)seckeychars, crypto_sign_SECRETKEYBYTES);
pubkey = string((char *)pubkeychars, crypto_sign_PUBLICKEYBYTES);
seckey = string((char *)seckeychars, crypto_sign_SECRETKEYBYTES);
}
/**
* Returns the signature bytes for a message.
*
* @param msg Message bytes to sign.
* @param seckey Secret key bytes.
* @return Signature bytes.
*/
string sign(const string &msg, const string &seckey)
{
//Generate the signature using libsodium.
@@ -42,6 +56,13 @@ string sign(const string &msg, const string &seckey)
return sig;
}
/**
* Returns the base64 signature string for a message.
*
* @param msg Base64 message string to sign.
* @param seckey Base64 secret key string.
* @return Base64 signature string.
*/
string sign_b64(const string &msg, const string &seckeyb64)
{
//Decode b64 string and generate the signature using libsodium.
@@ -57,12 +78,28 @@ string sign_b64(const string &msg, const string &seckeyb64)
return sigb64;
}
/**
* Verifies the given signature bytes for the message.
*
* @param msg Message bytes.
* @param sig Signature bytes.
* @param pubkey Public key bytes.
* @return 0 for successful verification. -1 for failure.
*/
int verify(const string &msg, const string &sig, const string &pubkey)
{
return crypto_sign_verify_detached(
(unsigned char *)sig.data(), (unsigned char *)msg.data(), msg.length(), (unsigned char *)pubkey.data());
}
/**
* Verifies the given base64 signature for the message.
*
* @param msg Base64 message string.
* @param sig Base64 signature string.
* @param pubkey Base64 secret key.
* @return 0 for successful verification. -1 for failure.
*/
int verify_b64(const string &msg, const string &sigb64, const string &pubkeyb64)
{
//Decode b64 string and verify the signature using libsodium.