* Implement --use-random and --use-urandom for luksFormat to allow setting of RNG...
[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 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
37         return vk;
38 }
39
40 void crypt_free_volume_key(struct volume_key *vk)
41 {
42         if (vk) {
43                 memset(vk->key, 0, vk->keylength);
44                 vk->keylength = 0;
45                 free(vk);
46         }
47 }
48
49 struct volume_key *crypt_generate_volume_key(struct crypt_device *cd, unsigned keylength)
50 {
51         int r;
52         struct volume_key *vk;
53
54         vk = crypt_alloc_volume_key(keylength, NULL);
55         if (!vk)
56                 return NULL;
57
58         r = crypt_random_get(cd, vk->key, keylength, CRYPT_RND_KEY);
59         if(r < 0) {
60                 crypt_free_volume_key(vk);
61                 return NULL;
62         }
63         return vk;
64 }