Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encryption using libsodium

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);
like image 750
kevinlindkvist Avatar asked Mar 17 '14 09:03

kevinlindkvist


1 Answers

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.

like image 188
Frank Denis Avatar answered Sep 20 '22 07:09

Frank Denis