forked from liexusong/php-beast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaes_algo_handler.c
91 lines (69 loc) · 1.38 KB
/
aes_algo_handler.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
90
91
#include <stdlib.h>
#include <string.h>
#include "beast_module.h"
#include "aes_algo_lib.c"
static uint8_t key[] = {
0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c,
};
int aes_encrypt_handler(char *inbuf, int len,
char **outbuf, int *outlen)
{
int blocks, i;
char *out;
char in[16];
blocks = len / 16;
if (len % 16) { /* not enough one block (16 bytes) */
blocks += 1;
}
out = malloc(blocks * 16);
if (!out) {
return -1;
}
for (i = 0; i < blocks; i++) {
int size;
memset(in, 0, 16);
if (i == blocks - 1 && (len % 16)) { /* the last block */
size = len % 16;
} else {
size = 16;
}
memcpy(in, inbuf + i * 16, size);
AES128_ECB_encrypt(in, key, out + i * 16);
}
*outbuf = out;
*outlen = blocks * 16;
return 0;
}
int aes_decrypt_handler(char *inbuf, int len,
char **outbuf, int *outlen)
{
int blocks, i;
char *out;
if (len % 16) {
return -1;
}
blocks = len / 16;
out = malloc(blocks * 16);
if (!out) {
return -1;
}
for (i = 0; i < blocks; i++) {
AES128_ECB_decrypt(inbuf + i * 16, key, out + i * 16);
}
*outbuf = out;
*outlen = blocks * 16;
return 0;
}
void aes_free_handler(void *ptr)
{
if (ptr) {
free(ptr);
}
}
struct beast_ops aes_handler_ops = {
.name = "aes-algo",
.encrypt = aes_encrypt_handler,
.decrypt = aes_decrypt_handler,
.free = aes_free_handler,
};