f533ad33ab6da14bd355cea5c356c31e44c28ab2
[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-2012, 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include <string.h>
22 #include <stdlib.h>
23
24 #include "internal.h"
25
26 struct volume_key *crypt_alloc_volume_key(unsigned keylength, const char *key)
27 {
28         struct volume_key *vk = malloc(sizeof(*vk) + keylength);
29
30         if (!vk)
31                 return NULL;
32
33         vk->keylength = keylength;
34         if (key)
35                 memcpy(&vk->key, key, keylength);
36         else
37                 memset(&vk->key, 0, 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(struct crypt_device *cd, 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 = crypt_random_get(cd, vk->key, keylength, CRYPT_RND_KEY);
61         if(r < 0) {
62                 crypt_free_volume_key(vk);
63                 return NULL;
64         }
65         return vk;
66 }