refactored sodium_crypto_secretbox() into separate source file.

This commit is contained in:
Heiko Reese
2021-08-11 05:28:39 +02:00
parent f5727effcf
commit 1e2ec834d2
4 changed files with 83 additions and 57 deletions

View File

@ -0,0 +1,69 @@
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sodium.h>
/* Local encryption key */
#include "recipient_pk.h"
/* Exim4 dlfunc API header */
#include <local_scan.h>
/*
* Encrypt the second argument with password from the first argument
*/
int sodium_crypto_secretbox(uschar ** yield, int argc, uschar * argv[])
{
if (sodium_init() == -1) {
*yield = string_copy(US "Unable to initialize libsodium");
return ERROR;
}
if (argc != 2) {
*yield =
string_sprintf
("Wrong number of arguments (got %i, expected 2)", argc);
return ERROR;
}
// get password
unsigned char *password = argv[0];
size_t passwordlen = strlen((const char *)password);
// get cleartext message
unsigned char *message = argv[1];
size_t messagelen = strlen((const char *)message);
/*
* Derive a key from the password.
* This operations needs to be fast (exim holds no state, this might be called once or mutliple times per email).
* Collisions avoidance or brute force arracks are not a concern here.
*/
unsigned char keybytes[crypto_secretbox_KEYBYTES];
sodium_memzero(keybytes, crypto_secretbox_KEYBYTES);
crypto_generichash(keybytes, crypto_secretbox_KEYBYTES,
password, passwordlen, NULL, 0);
// prepare buffer for ciphertext
unsigned int cipherlen = messagelen + crypto_secretbox_MACBYTES;
unsigned char *ciphertext = malloc(cipherlen);
sodium_memzero(ciphertext, cipherlen);
// encrypt message
unsigned char nonce[crypto_secretbox_NONCEBYTES];
randombytes_buf(nonce, sizeof nonce);
crypto_secretbox_easy(ciphertext, message, messagelen, nonce, keybytes);
// base64-encode the ciphertext
unsigned int outputsize = sodium_base64_ENCODED_LEN(cipherlen,
sodium_base64_VARIANT_ORIGINAL);
unsigned char *outstring = malloc(outputsize);
sodium_memzero(outstring, outputsize);
sodium_bin2base64((char *const)outstring, outputsize,
ciphertext, cipherlen,
sodium_base64_VARIANT_ORIGINAL);
free(ciphertext);
// return base64-encoded ciphertext
*yield = string_copy(outstring);
free(outstring);
return OK;
}