2 * cryptsetup plain device helper functions
4 * Copyright (C) 2004 Jana Saout <jana@saout.de>
5 * Copyright (C) 2010-2021 Red Hat, Inc. All rights reserved.
6 * Copyright (C) 2010-2021 Milan Broz
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include "libcryptsetup.h"
30 static int hash(const char *hash_name, size_t key_size, char *key,
31 size_t passphrase_size, const char *passphrase)
33 struct crypt_hash *md = NULL;
37 if (crypt_hash_init(&md, hash_name))
40 len = crypt_hash_size(hash_name);
42 for(round = 0; key_size && !r; round++) {
43 /* hack from hashalot to avoid null bytes in key */
44 for(i = 0; i < round; i++)
45 if (crypt_hash_write(md, "A", 1))
48 if (crypt_hash_write(md, passphrase, passphrase_size))
54 if (crypt_hash_final(md, key, len))
61 crypt_hash_destroy(md);
65 #define PLAIN_HASH_LEN_MAX 256
67 int crypt_plain_hash(struct crypt_device *cd,
68 const char *hash_name,
69 char *key, size_t key_size,
70 const char *passphrase, size_t passphrase_size)
72 char hash_name_buf[PLAIN_HASH_LEN_MAX], *s;
73 size_t hash_size, pad_size;
76 log_dbg(cd, "Plain: hashing passphrase using %s.", hash_name);
78 if (strlen(hash_name) >= PLAIN_HASH_LEN_MAX)
80 strncpy(hash_name_buf, hash_name, PLAIN_HASH_LEN_MAX);
81 hash_name_buf[PLAIN_HASH_LEN_MAX - 1] = '\0';
83 /* hash[:hash_length] */
84 if ((s = strchr(hash_name_buf, ':'))) {
87 if (!*s || sscanf(s, "%zd", &hash_size) != 1) {
88 log_dbg(cd, "Hash length is not a number");
91 if (hash_size > key_size) {
92 log_dbg(cd, "Hash length %zd > key length %zd",
96 pad_size = key_size - hash_size;
102 /* No hash, copy passphrase directly */
103 if (!strcmp(hash_name_buf, "plain")) {
104 if (passphrase_size < hash_size) {
105 log_dbg(cd, "Too short plain passphrase.");
108 memcpy(key, passphrase, hash_size);
111 r = hash(hash_name_buf, hash_size, key, passphrase_size, passphrase);
113 if (r == 0 && pad_size)
114 memset(key + hash_size, 0, pad_size);