2 * cryptsetup volume key implementation
4 * Copyright (C) 2004-2006 Clemens Fruhwirth <clemens@endorphin.org>
5 * Copyright (C) 2010-2023 Red Hat, Inc. All rights reserved.
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 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
29 struct volume_key *crypt_alloc_volume_key(size_t keylength, const char *key)
31 struct volume_key *vk;
33 if (keylength > (SIZE_MAX - sizeof(*vk)))
36 vk = malloc(sizeof(*vk) + keylength);
40 vk->key_description = NULL;
41 vk->keylength = keylength;
45 /* keylength 0 is valid => no key */
48 memcpy(&vk->key, key, keylength);
50 crypt_safe_memzero(&vk->key, keylength);
56 int crypt_volume_key_set_description(struct volume_key *vk, const char *key_description)
61 free(CONST_CAST(void*)vk->key_description);
62 vk->key_description = NULL;
63 if (key_description && !(vk->key_description = strdup(key_description)))
69 void crypt_volume_key_set_id(struct volume_key *vk, int id)
75 int crypt_volume_key_get_id(const struct volume_key *vk)
77 return vk ? vk->id : -1;
80 struct volume_key *crypt_volume_key_by_id(struct volume_key *vks, int id)
82 struct volume_key *vk = vks;
87 while (vk && vk->id != id)
93 void crypt_volume_key_add_next(struct volume_key **vks, struct volume_key *vk)
95 struct volume_key *tmp;
113 struct volume_key *crypt_volume_key_next(struct volume_key *vk)
115 return vk ? vk->next : NULL;
118 void crypt_free_volume_key(struct volume_key *vk)
120 struct volume_key *vk_next;
123 crypt_safe_memzero(vk->key, vk->keylength);
125 free(CONST_CAST(void*)vk->key_description);
132 struct volume_key *crypt_generate_volume_key(struct crypt_device *cd, size_t keylength)
135 struct volume_key *vk;
137 vk = crypt_alloc_volume_key(keylength, NULL);
141 r = crypt_random_get(cd, vk->key, keylength, CRYPT_RND_KEY);
143 crypt_free_volume_key(vk);