【发布时间】:2022-08-14 19:46:22
【问题描述】:
我有一个正在开发的文件加密程序,我已经能够根据用户提供的密码和正确加密的文件内容(据我所知)建立密钥。但是,当我尝试解密内容作为测试以确保我的代码正常工作时,它会成功,但输出时只会产生密文而不是纯文本。我使用的代码是:
#include <errno.h>
#include <sodium.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getFileData(const char *filename, char **dataBuffer);
int main(void){
unsigned char *filename = \"file.txt\";
char *contents = NULL;
int contentLength;
getFileData(filename, &contents);
contentLength = strlen(contents);
// Using sodium\'s key derivation to make a key for secretbox
char *password = \"Passw0rd!\"; // Won\'t actually hardcode password
int keylen = crypto_box_SEEDBYTES;
unsigned char salt[crypto_pwhash_SALTBYTES];
unsigned char key[keylen];
randombytes_buf(salt, sizeof(salt));
if (crypto_pwhash(key, sizeof(key), password, strlen(password), salt, crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE, crypto_pwhash_ALG_DEFAULT) != 0){
perror(\"[ERROR]\");
exit(EXIT_FAILURE);
}
printf(\"%s\\n\", key);
// -------------------------------------------------------------------
int ctlen = crypto_secretbox_MACBYTES + contentLength;
unsigned char nonce[crypto_secretbox_NONCEBYTES];
unsigned char ciphertext[ctlen];
randombytes_buf(nonce, sizeof nonce);
// Encrypting plaintext
crypto_secretbox_easy(ciphertext, contents, contentLength, nonce, key);
printf(\"%s\\n\", ciphertext);
// Decrypting ciphertext
unsigned char decrypted[contentLength];
if (crypto_secretbox_open_easy(decrypted, ciphertext, ctlen, nonce, key) != 0){
perror(\"[FAILED]\");
exit(EXIT_FAILURE);
}
printf(\"%s\\n\", decrypted);
return 0;
}
我最后得到的输出是:
When I print out the ciphertext -> ?ٝ,�N2/ہ���Lj�k~�z��2v*|�c��Z��|�-��&��
When I print out the plaintext -> ?ٝ,�N2/ہ���Lj�k~�z��2v*|�c��Z��|�-��&��
我不确定为什么它成功但没有实际解密发生?
-
你能在getFileData之后打印出内容吗?看起来您没有为指针内容分配内存。
-
是的,我可以,它是一个我没有包含的函数,但它确实为指针创造了空间。
标签: c encryption libsodium