-
Notifications
You must be signed in to change notification settings - Fork 0
/
decrypt.c
89 lines (72 loc) · 1.87 KB
/
decrypt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* decrypt.c
*
* a demo for libgcrypt
*
*/
#include "crypt_demo.h"
/* print usage if the argument is wrong */
void usage_print(char * command){
printf("Usage: %s filename\n",command);
}
int main(int argc,char *argv[])
{
if (argc!=2){
usage_print(argv[0]);
return 1;
}
FILE *fin=fopen(argv[1],"rb");
FILE *fout;
gcry_cipher_hd_t cipher_hd;
gcry_error_t cipher_err;
int file_size=get_file_size(argv[1]);
char *input_buf= (char*)malloc(file_size);
memset(input_buf,0,file_size);
// encry text buffer
size_t key_size = gcry_cipher_get_algo_keylen(CIPHER_ALGO);
size_t block_size = gcry_cipher_get_algo_blklen(CIPHER_ALGO);
char *decry_buf=malloc(file_size);
char *iv=malloc(block_size);
memset(iv,0,block_size);
memcpy(iv,MAGIC_STRING,sizeof(MAGIC_STRING));
char *key = get_key_from_password1();
printf("key = %s",key);
//open cipher
cipher_err=gcry_cipher_open(&cipher_hd,CIPHER_ALGO,
GCRY_CIPHER_MODE_CBC,GCRY_CIPHER_CBC_CTS);
if (cipher_err){
cipher_error_handler(cipher_err);
}
//set key
cipher_err=gcry_cipher_setkey(cipher_hd,key,key_size);
if (cipher_err){
cipher_error_handler(cipher_err);
}
//set iv
cipher_err=gcry_cipher_setiv(cipher_hd, iv, block_size);
if (cipher_err){
cipher_error_handler(cipher_err);
}
// mkstemp(".temp");
char *outfilename=malloc(5+strlen(argv[1]));
strcpy(outfilename,argv[1]);
strcat(outfilename,".dec");
char *name = (char*)malloc(strlen(outfilename)+10);
strcpy(name,".temp/");
strcat(name,outfilename);
printf("%s\n",name);
fout = fopen(name,"wb");
//decrypt
fread(decry_buf,1,file_size,fin);
cipher_err=gcry_cipher_decrypt(cipher_hd,decry_buf,file_size,NULL,0);
while (decry_buf[file_size-1]==0){
file_size--;
}
if (cipher_err){
cipher_error_handler(cipher_err);
}
fwrite(decry_buf,1,file_size,fout);
gcry_cipher_close(cipher_hd);
fclose(fin);
fclose(fout);
return 0;
}