Reputation: 183
I have been struggling to encrypt/decrypt some data using crypto_secretbox_easy() in libsodium. I can't seem to find any good documentation on the usage.
I want to get a password from the user, use that to somehow make a key, then encrypt/decrypt the data using that.
The problem with the toy code that I have posted below is that the crypto_secretbox_open_easy() returns -1 from within verify_16.c. Does anyone have any idea where I could find source showing how to use this interface or what could be going wrong? Thanks!
unsigned char * cipher;
unsigned char * decoded;
unsigned char * message;
unsigned long long message_len = 32;
size_t noncelen = sizeof(char) * crypto_secretbox_noncebytes();
size_t keylen = sizeof(char) * crypto_secretbox_keybytes();
unsigned char * nonce = calloc(noncelen, noncelen);
unsigned char * key = calloc(keylen, keylen);
message = calloc(32*sizeof(char), sizeof(char) * 32);
cipher = calloc(32*sizeof(char), sizeof(char) * 32);
decoded = calloc(32*sizeof(char), sizeof(char) * 32);
crypto_secretbox_easy((unsigned char *)cipher, (const unsigned char *)message,
message_len, nonce, key);
crypto_secretbox_open_easy((unsigned char *)decoded, (const unsigned char *) cipher,
message_len, nonce, key);
Upvotes: 6
Views: 4409
Reputation: 1501
The test/secretbox_easy2.c file
(in the sodium source code) shows how to use it:
randombytes_buf(nonce, sizeof nonce);
crypto_secretbox_easy(c, m, mlen, nonce, k);
crypto_secretbox_open_easy(decoded, c, mlen + crypto_secretbox_MACBYTES,
nonce, k);
In order to derive a key from a password, sodium provides crypto_pwhash_scryptsalsa208sha256
.
Upvotes: 3
Reputation: 4832
the size of cipher should be 16 bytes larger then message for the MAC bytes, so alloc 16 more bytes and on open_easy just add + 16 to the message_len.
Also take a look, your call to calloc actually allocate a lot memory than needed, because calloc do the multiplying inside the method.
Upvotes: 1