3
我試圖將加密數據寫入文件。但是,當它重新讀入程序並嘗試解密時,我只會將垃圾回收。沒有寫入文件似乎工作..我做錯了什麼?Mcrypt庫寫入文件的結果
下面的代碼:
MCRYPT td, td2;
char * string = "My secret message";
int i;
char *key; /* created using mcrypt_gen_key */
char *IV;
char * block_buffer;
int blocksize;
int keysize = 32; /* 192 bits == 24 bytes */
key = calloc(1, keysize);
strcpy(key, "This-is-my-key#########");
td = mcrypt_module_open("saferplus", NULL, "cbc", NULL);
td2 = mcrypt_module_open("saferplus", NULL, "cbc", NULL);
blocksize = mcrypt_enc_get_block_size(td);
block_buffer = malloc(blocksize);
IV=malloc(mcrypt_enc_get_iv_size(td));
for (i=0; i < mcrypt_enc_get_iv_size(td); i++) {
IV[i]=rand();
}
mcrypt_generic_init(td, key, keysize, IV);
mcrypt_generic_init(td2, key, keysize, IV);
strcpy(block_buffer, string);
printf("1: %s\n", block_buffer);
mcrypt_generic (td, block_buffer, blocksize);
FILE *myFile;
myFile = fopen("encrypted","ab");
fwrite(block_buffer, 1, blocksize, myFile);
fclose(myFile);
printf("2: %s\n", block_buffer);
myFile = fopen("encrypted","rb");
fread(block_buffer, 1, blocksize, myFile);
fclose(myFile);
printf("2.5: %s\n", block_buffer);
mdecrypt_generic (td2, block_buffer, blocksize);
printf("3: %s\n", block_buffer);
/* deinitialize the encryption thread */
mcrypt_generic_deinit (td);
mcrypt_generic_deinit(td2);
/* Unload the loaded module */
mcrypt_module_close(td);
mcrypt_module_close(td2);
return 0;
爲什麼要打開文件來追加('myFile = fopen(「encrypted」,「ab」);')而不是簡單的書寫?運行程序時文件是否已經存在?你有沒有比較'加密'hexdump與你的內存緩衝區? – 2011-05-04 00:57:13
謝謝畝,我第一次打開它只是使用一個。我想也許有些信息會因爲格式化而丟失,所以我想嘗試保存並以二進制打開它,看看它是否會有所作爲。我如何去做一個hexdump?一個教程的鏈接就足夠了。 – 2011-05-04 11:09:02