2 * QEMU Crypto cipher algorithms
4 * Copyright (c) 2015 Red Hat, Inc.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library 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 GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 #include "qemu/osdep.h"
22 #include "crypto/cipher.h"
25 static size_t alg_key_len
[QCRYPTO_CIPHER_ALG__MAX
] = {
26 [QCRYPTO_CIPHER_ALG_AES_128
] = 16,
27 [QCRYPTO_CIPHER_ALG_AES_192
] = 24,
28 [QCRYPTO_CIPHER_ALG_AES_256
] = 32,
29 [QCRYPTO_CIPHER_ALG_DES_RFB
] = 8,
32 static size_t alg_block_len
[QCRYPTO_CIPHER_ALG__MAX
] = {
33 [QCRYPTO_CIPHER_ALG_AES_128
] = 16,
34 [QCRYPTO_CIPHER_ALG_AES_192
] = 16,
35 [QCRYPTO_CIPHER_ALG_AES_256
] = 16,
36 [QCRYPTO_CIPHER_ALG_DES_RFB
] = 8,
39 static bool mode_need_iv
[QCRYPTO_CIPHER_MODE__MAX
] = {
40 [QCRYPTO_CIPHER_MODE_ECB
] = false,
41 [QCRYPTO_CIPHER_MODE_CBC
] = true,
45 size_t qcrypto_cipher_get_block_len(QCryptoCipherAlgorithm alg
)
47 if (alg
>= G_N_ELEMENTS(alg_key_len
)) {
50 return alg_block_len
[alg
];
54 size_t qcrypto_cipher_get_key_len(QCryptoCipherAlgorithm alg
)
56 if (alg
>= G_N_ELEMENTS(alg_key_len
)) {
59 return alg_key_len
[alg
];
63 size_t qcrypto_cipher_get_iv_len(QCryptoCipherAlgorithm alg
,
64 QCryptoCipherMode mode
)
66 if (alg
>= G_N_ELEMENTS(alg_block_len
)) {
69 if (mode
>= G_N_ELEMENTS(mode_need_iv
)) {
73 if (mode_need_iv
[mode
]) {
74 return alg_block_len
[alg
];
81 qcrypto_cipher_validate_key_length(QCryptoCipherAlgorithm alg
,
85 if ((unsigned)alg
>= QCRYPTO_CIPHER_ALG__MAX
) {
86 error_setg(errp
, "Cipher algorithm %d out of range",
91 if (alg_key_len
[alg
] != nkey
) {
92 error_setg(errp
, "Cipher key length %zu should be %zu",
93 nkey
, alg_key_len
[alg
]);
99 #if defined(CONFIG_GCRYPT) || defined(CONFIG_NETTLE)
101 qcrypto_cipher_munge_des_rfb_key(const uint8_t *key
,
104 uint8_t *ret
= g_new0(uint8_t, nkey
);
106 for (i
= 0; i
< nkey
; i
++) {
108 r
= (r
& 0xf0) >> 4 | (r
& 0x0f) << 4;
109 r
= (r
& 0xcc) >> 2 | (r
& 0x33) << 2;
110 r
= (r
& 0xaa) >> 1 | (r
& 0x55) << 1;
115 #endif /* CONFIG_GCRYPT || CONFIG_NETTLE */
118 #include "crypto/cipher-gcrypt.c"
119 #elif defined CONFIG_NETTLE
120 #include "crypto/cipher-nettle.c"
122 #include "crypto/cipher-builtin.c"