Generalise volume key struct.
[platform/upstream/cryptsetup.git] / lib / volumekey.c
1 /*
2  * cryptsetup volume key implementation
3  *
4  * Copyright (C) 2004-2006, Clemens Fruhwirth <clemens@endorphin.org>
5  * Copyright (C) 2010 Red Hat, Inc. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * version 2 as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <string.h>
22 #include <stdlib.h>
23
24 #include "internal.h"
25
26 int getRandom(char *buf, size_t len);
27
28 struct volume_key *crypt_alloc_volume_key(unsigned keylength, const char *key)
29 {
30         struct volume_key *vk = malloc(sizeof(*vk) + keylength);
31
32         if (!vk)
33                 return NULL;
34
35         vk->keylength = keylength;
36         if (key)
37                 memcpy(&vk->key, key, keylength);
38
39         return vk;
40 }
41
42 void crypt_free_volume_key(struct volume_key *vk)
43 {
44         if (vk) {
45                 memset(vk->key, 0, vk->keylength);
46                 vk->keylength = 0;
47                 free(vk);
48         }
49 }
50
51 struct volume_key *crypt_generate_volume_key(unsigned keylength)
52 {
53         int r;
54         struct volume_key *vk;
55
56         vk = crypt_alloc_volume_key(keylength, NULL);
57         if (!vk)
58                 return NULL;
59
60         r = getRandom(vk->key, keylength);
61         if(r < 0) {
62                 crypt_free_volume_key(vk);
63                 return NULL;
64         }
65         return vk;
66 }
67