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
|
#include <stdlib.h>
#include <string.h>
#include "crypto_buffer.h"
#include <stdio.h>
int crypto_buffer_init(crypto_buffer *s, int fd, operation op, u32 blocks, int type, u8 *key, u32 key_len)
{
int ret;
int size;
if(blocks<3) return -1; /* magic + info + data */
s->fd = fd;
s->op = op;
if(type & BLOWFISH){
size = BF_BLOCK_SIZE;
ret = blowfish_setkey((struct blowfish_ctx*)&s->ctx, key, key_len, 0);
if(type & DECRYPT){ s->cipher = blowfish_decrypt; }
else { s->cipher = blowfish_encrypt; }
}
else if(type & TWOFISH){
size = TF_BLOCK_SIZE;
ret = twofish_setkey((struct twofish_ctx*)&s->ctx, key, key_len, 0);
if(type & DECRYPT) { s->cipher = twofish_decrypt; }
else {s->cipher = twofish_encrypt; }
}
else if(type & AES){
size = AES_BLOCK_SIZE;
ret = aes_setkey((struct aes_ctx*)&s->ctx, key, key_len, 0);
if(type & DECRYPT) { s->cipher = aes_decrypt; }
else {s->cipher = aes_encrypt; }
}
else if(type & DES){
size = DES_BLOCK_SIZE;
ret = des_setkey((struct des_ctx*)&s->ctx, key, key_len, 0);
if(type & DECRYPT) { s->cipher = des_decrypt; }
else {s->cipher = des_encrypt; }
}
else if(type & DES3_EDE){
size = DES3_EDE_BLOCK_SIZE;
ret = des3_ede_setkey((struct des3_ede_ctx*)&s->ctx, key, key_len, 0);
if(type & DECRYPT) { s->cipher = des3_ede_decrypt; }
else {s->cipher = des3_ede_encrypt; }
}
else return -1;
if(ret!=0) return -1;
if((U32_MAX / size) < blocks) return -1;
s->block_size = size;
s->e_len = size * blocks; /* TODO check overflow */
s->data_st.bytes = s->data_st.strlen = 0;
/* clear buffer */
s->c_buffer = malloc(size);
if(s->c_buffer==NULL) return -1;
s->c_ptr = s->c_buffer;
s->c_end = s->c_buffer + size;
/* encrypte buffer */
s->e_buffer = malloc(s->e_len);
if(s->e_buffer==NULL) return -1;
memset(s->e_buffer,0x5a,size); /* for write operation */
s->e_data = (struct info*)(s->e_buffer + size);
s->e_end = s->e_buffer + s->e_len;
if(type & DECRYPT){
s->e_ptr = s->e_buffer;
}
else{
s->e_ptr = s->e_buffer + (size << 1);
s->e_len -= (size << 1);
}
/*
fprintf(stderr,"e_buffer : %x\n",s->e_buffer);
fprintf(stderr,"e_data : %x\n",s->e_data);
fprintf(stderr,"e_ptr : %x\n",s->e_ptr);
fprintf(stderr,"e_end : %x\n",s->e_end);
fprintf(stderr,"length : %d\n",s->e_len);
*/
return ret;
}
|