29 #include <stdio.h> |
29 #include <stdio.h> |
30 #include <stdlib.h> |
30 #include <stdlib.h> |
31 #include <string.h> |
31 #include <string.h> |
32 #include <openssl/rand.h> |
32 #include <openssl/rand.h> |
33 |
33 |
|
34 #include <libidav/utils.h> |
34 #include "crypto.h" |
35 #include "crypto.h" |
35 |
36 |
36 AESDecrypter* aes_decrypter_new(Key *key, void *stream, dav_write_func write_func) { |
37 AESDecrypter* aes_decrypter_new(Key *key, void *stream, dav_write_func write_func) { |
37 AESDecrypter *dec = malloc(sizeof(AESDecrypter)); |
38 AESDecrypter *dec = malloc(sizeof(AESDecrypter)); |
38 dec->stream = stream; |
39 dec->stream = stream; |
190 free(enc->tmp); |
191 free(enc->tmp); |
191 } |
192 } |
192 EVP_CIPHER_CTX_cleanup(&enc->ctx); |
193 EVP_CIPHER_CTX_cleanup(&enc->ctx); |
193 free(enc); |
194 free(enc); |
194 } |
195 } |
|
196 |
|
197 |
|
198 char* aes_encrypt(char *in, Key *key) { |
|
199 char *iv = malloc(16); |
|
200 if(!RAND_bytes(iv, 16)) { |
|
201 free(iv); |
|
202 return NULL; |
|
203 } |
|
204 |
|
205 EVP_CIPHER_CTX ctx; |
|
206 EVP_CIPHER_CTX_init(&ctx); |
|
207 if(key->type == KEY_AES128) { |
|
208 EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key->data, iv); |
|
209 } else if(key->type == KEY_AES256) { |
|
210 EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key->data, iv); |
|
211 } else { |
|
212 return NULL; |
|
213 } |
|
214 |
|
215 int len = strlen(in); |
|
216 int buflen = len + 64; |
|
217 char *buf = calloc(1, buflen); |
|
218 memcpy(buf, iv, 16); |
|
219 |
|
220 int l = buflen - 16; |
|
221 EVP_EncryptUpdate(&ctx, buf + 16, &l, in, len); |
|
222 |
|
223 int f = 0; |
|
224 EVP_EncryptFinal_ex(&ctx, buf + 16 + l, &f); |
|
225 char *out = util_base64encode(buf, 16 + l + f); |
|
226 free(buf); |
|
227 return out; |
|
228 } |
|
229 |
|
230 char* aes_decrypt(char *in, Key *key) { |
|
231 int len; |
|
232 char *buf = util_base64decode_len(in, &len); |
|
233 |
|
234 EVP_CIPHER_CTX ctx; |
|
235 EVP_CIPHER_CTX_init(&ctx); |
|
236 if(key->type == KEY_AES128) { |
|
237 EVP_DecryptInit_ex( |
|
238 &ctx, |
|
239 EVP_aes_128_cbc(), |
|
240 NULL, |
|
241 key->data, |
|
242 buf); |
|
243 } else if(key->type == KEY_AES256) { |
|
244 EVP_DecryptInit_ex( |
|
245 &ctx, |
|
246 EVP_aes_256_cbc(), |
|
247 NULL, |
|
248 key->data, |
|
249 buf); |
|
250 } else { |
|
251 return NULL; |
|
252 } |
|
253 |
|
254 char *out = malloc(len + 1); |
|
255 int outlen = len; |
|
256 char *in_buf = buf + 16; |
|
257 int inlen = len - 16; |
|
258 int f = 0; |
|
259 |
|
260 |
|
261 |
|
262 EVP_DecryptUpdate(&ctx, out, &outlen, in_buf, inlen); |
|
263 EVP_DecryptFinal_ex(&ctx, out + outlen, &f); |
|
264 out[outlen + f] = '\0'; |
|
265 free(buf); |
|
266 return out; |
|
267 } |
|
268 |