summaryrefslogtreecommitdiff
path: root/lib/lib2.c
blob: fe65bb846f4a96aa1380b8ac4c5e9e87b6220b10 (plain)
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
#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;
}

/**
 * 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;

}