iv_gen: Provide external sequence number (IKE, ESP)
[strongswan.git] / src / libstrongswan / crypto / iv / iv_gen_seq.c
1 /*
2 * Copyright (C) 2013 Tobias Brunner
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "iv_gen_seq.h"
17
18 typedef struct private_iv_gen_t private_iv_gen_t;
19
20 /**
21 * Private data of an iv_gen_t object.
22 */
23 struct private_iv_gen_t {
24
25 /**
26 * Public iv_gen_t interface.
27 */
28 iv_gen_t public;
29 };
30
31 METHOD(iv_gen_t, get_iv, bool,
32 private_iv_gen_t *this, u_int64_t seq, size_t size, u_int8_t *buffer)
33 {
34 u_int8_t iv[sizeof(u_int64_t)];
35 size_t len = size;
36
37 if (len > sizeof(u_int64_t))
38 {
39 len = sizeof(u_int64_t);
40 memset(buffer, 0, size - len);
41 }
42 htoun64(iv, seq);
43 memcpy(buffer + size - len, iv + sizeof(u_int64_t) - len, len);
44 return TRUE;
45 }
46
47 METHOD(iv_gen_t, allocate_iv, bool,
48 private_iv_gen_t *this, u_int64_t seq, size_t size, chunk_t *chunk)
49 {
50 *chunk = chunk_alloc(size);
51 if (!get_iv(this, seq, chunk->len, chunk->ptr))
52 {
53 chunk_free(chunk);
54 return FALSE;
55 }
56 return TRUE;
57 }
58
59 METHOD(iv_gen_t, destroy, void,
60 private_iv_gen_t *this)
61 {
62 free(this);
63 }
64
65 iv_gen_t *iv_gen_seq_create()
66 {
67 private_iv_gen_t *this;
68
69 INIT(this,
70 .public = {
71 .get_iv = _get_iv,
72 .allocate_iv = _allocate_iv,
73 .destroy = _destroy,
74 },
75 );
76
77 return &this->public;
78 }