d8a5a29094a30083f12762cbe3a33cb9d3852384
[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 * sequence number
32 */
33 u_int64_t seq;
34 };
35
36 METHOD(iv_gen_t, get_iv, bool,
37 private_iv_gen_t *this, size_t size, u_int8_t *buffer)
38 {
39 u_int8_t iv[sizeof(u_int64_t)];
40 size_t len = size;
41
42 if (this->seq == UINT64_MAX || len < sizeof(u_int64_t))
43 {
44 return FALSE;
45 }
46 if (len > sizeof(u_int64_t))
47 {
48 len = sizeof(u_int64_t);
49 memset(buffer, 0, size - len);
50 }
51 htoun64(iv, this->seq++);
52 memcpy(buffer + size - len, iv + sizeof(u_int64_t) - len, len);
53 return TRUE;
54 }
55
56 METHOD(iv_gen_t, allocate_iv, bool,
57 private_iv_gen_t *this, size_t size, chunk_t *chunk)
58 {
59 *chunk = chunk_alloc(size);
60 if (!get_iv(this, chunk->len, chunk->ptr))
61 {
62 chunk_free(chunk);
63 return FALSE;
64 }
65 return TRUE;
66 }
67
68 METHOD(iv_gen_t, destroy, void,
69 private_iv_gen_t *this)
70 {
71 free(this);
72 }
73
74 iv_gen_t *iv_gen_seq_create()
75 {
76 private_iv_gen_t *this;
77
78 INIT(this,
79 .public = {
80 .get_iv = _get_iv,
81 .allocate_iv = _allocate_iv,
82 .destroy = _destroy,
83 },
84 );
85
86 return &this->public;
87 }