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
|
#include "lib2.h"
#include "lib.h"
/**
* appends PKCS#7 padding to string. devide string in blocks of size blocksize
* and append to last block so that it is also of blocksize length
*/
char *pkcs7_padding(char *string, int length_string, int blocksize)
{
char *result = NULL;
int i;
int value = blocksize - (length_string % blocksize);
result = malloc(length_string+value+1);
memcpy(result, string, length_string);
for(i=0;i<value;i++) {
result[length_string+i] = (char) value;
}
result[length_string+i] = '\0';
return result;
}
/**
* unpadd a string
* @param in string which should be unpadded
* @param length_in length of paramter length_in
* @param unpadded place where the unpadded text should be stored
* @param blocksize size of the block to which should be padded
*/
int valid_pkcs7_padding(const char *in, int length_in, char *unpadded, int blocksize)
{
int i, padding_length;
// look how many equal bytes are at the end
// ignore last byte \0
for(i=length_in-1;i>0;i--) {
if(in[i] != in[i-1])
break;
}
padding_length = length_in - i;
if ((length_in % padding_length) != 0)
return 0;
if(in[length_in-1] != padding_length)
return 0;
memcpy(unpadded, in, (length_in-padding_length));
return 1;
}
/**
* decrypts content which is encrypted in AES CBC mode
* @param in input content
* @param length_in length of parametere in
* @param out place where the decrypted content should be written to
* @param string_key key with which the content in in has been decrypted
* @param iv initalization vector
*/
int aes_cbc(char *in, int length_in, char *out, unsigned char *string_key, char *init_vector)
{
char iv[16];
AES_KEY key;
int number_blocks = length_in / 16;
int i, j;
unsigned char ciphertext[128+1];
unsigned char tmp_after_aes[128+1];
unsigned char cleartext[128+1];
// set the key and bits
AES_set_decrypt_key(string_key, 128, &key);
memcpy(init_vector, iv, 16);
// implement cbc mode
for(i=0;i<number_blocks;i++) {
//do aes decryption
AES_decrypt(&in[i*16], tmp_after_aes, &key);
// xor
xor_string(iv, tmp_after_aes, &out[i*16], 16, 16);
// this ciphertext block is the next iv
for(j=0;j<16;j++) {
iv[j] = in[i*16+j];
}
}
return 0;
}
|