我一直在努力使用libsodium中的crypto_secretbox_easy()来加密/解密某些数据。我似乎无法找到有关用法的任何好文档。
我想从用户那里获取密码,使用它来以某种方式创建密钥,然后使用它来加密/解密数据。
我在下面发布的玩具代码的问题是crypto_secretbox_open_easy()从verify_16.c中返回-1。有没有人知道我在哪里可以找到如何使用这个界面或可能出错的来源?谢谢!
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);
答案 0 :(得分:2)
test/secretbox_easy2.c file
(在钠源代码中)显示了如何使用它:
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);
为了从密码中获取密钥,钠提供crypto_pwhash_scryptsalsa208sha256
。
答案 1 :(得分:1)
密码的大小应该比MAC字节的消息大16个字节,所以再分配16个字节,在open_easy上只需要向message_len添加+16。
另外看一下,你对calloc的调用实际上分配了很多内存而不是需要,因为calloc在方法内部进行了相乘。