aboutsummaryrefslogtreecommitdiff
path: root/crypto
diff options
context:
space:
mode:
authorRichard Henderson <richard.henderson@linaro.org>2022-05-26 07:00:04 -0700
committerRichard Henderson <richard.henderson@linaro.org>2022-05-26 07:00:04 -0700
commit2417cbd5916d043e0c56408221fbe9935d0bc8da (patch)
treed009a0ee2069fc201b499b198f508b68900d5df4 /crypto
parent58b53669e87fed0d70903e05cd42079fbbdbc195 (diff)
parentf0cfb761bc6e590d648b759e6bdb8c946062b5f5 (diff)
downloadqemu-2417cbd5916d043e0c56408221fbe9935d0bc8da.zip
qemu-2417cbd5916d043e0c56408221fbe9935d0bc8da.tar.gz
qemu-2417cbd5916d043e0c56408221fbe9935d0bc8da.tar.bz2
Merge tag 'ak-pull-request' of https://gitlab.com/berrange/qemu into staging
Merge asymmetric cipher crypto support This extends the internal crypto APIs to support the use of asymmetric ciphers. # -----BEGIN PGP SIGNATURE----- # # iQIzBAABCAAdFiEE2vOm/bJrYpEtDo4/vobrtBUQT98FAmKPWdgACgkQvobrtBUQ # T9/dXA//XozeQbIK9y/1wb60LXiqHiHDMi8Ct1oEpNsLaL4lsp09VjtmxggqMfad # MjxQjKdOVMVPISRnrKCJQ6qiGKQB7C/php1ZxOPdG4zgf2Ofl312GHZCLjqLkpB8 # KnhdFB31coI45EQ+agk5ZO8Baml85yY4sALLofGXV3xatJswH1HoMAmDATe5ebko # ox7qd/S9Q4bpZA4v+8fUbvX2zI95hZta8+4d2Irx542gO8KibYKRVmffJhcKx6hy # 4x7iTEaGQQn3DFMbVxsvb4wLwx1v8sSS6C2rHuGZY67ZzDnYhAdaHG9CaWR3uvtS # vs7EcEWqn45SfJ/FaYUyon/btsawJrXP9NISmns4J6TYoN6sJJVxk9T9A/hlqtEE # /iwTfp/Se+o2JDLgC+JHQz8maj4igloGNhF8+u4lXBLEpT7tlvaxhkrcPo9Um7ay # bWpmLoxVN5vEvOnsrfLhK6LGPIzfjP4tYX0xwWy5Lm/DZ1LinJOONPXjArFr3TaQ # rcS6L15ZaiFu9bYUyN1Uf7V7VydiVV8RlkuTqJ614gSX0v+GCMR1J+0WsQ4DtPlT # G6WP0EnnD4Ulg9XpSMte2GXKQ0d8c7hTKr3/RW+BuvvgP5T4P7guBTRhmufRiip6 # BByKpXrQ72yGm6U+nTtEVFdUWVER31U0ufsW64hdM+LGfiG7fUE= # =X589 # -----END PGP SIGNATURE----- # gpg: Signature made Thu 26 May 2022 03:43:36 AM PDT # gpg: using RSA key DAF3A6FDB26B62912D0E8E3FBE86EBB415104FDF # gpg: Good signature from "Daniel P. Berrange <dan@berrange.com>" [full] # gpg: aka "Daniel P. Berrange <berrange@redhat.com>" [full] * tag 'ak-pull-request' of https://gitlab.com/berrange/qemu: tests/crypto: Add test suite for RSA keys test/crypto: Add test suite for crypto akcipher crypto: Implement RSA algorithm by gcrypt crypto: Implement RSA algorithm by hogweed crypto: add ASN.1 DER decoder crypto: Introduce akcipher crypto class qapi: crypto-akcipher: Introduce akcipher types to qapi Signed-off-by: Richard Henderson <richard.henderson@linaro.org>
Diffstat (limited to 'crypto')
-rw-r--r--crypto/akcipher-gcrypt.c.inc595
-rw-r--r--crypto/akcipher-nettle.c.inc451
-rw-r--r--crypto/akcipher.c108
-rw-r--r--crypto/akcipherpriv.h55
-rw-r--r--crypto/der.c189
-rw-r--r--crypto/der.h81
-rw-r--r--crypto/meson.build6
-rw-r--r--crypto/rsakey-builtin.c.inc200
-rw-r--r--crypto/rsakey-nettle.c.inc158
-rw-r--r--crypto/rsakey.c44
-rw-r--r--crypto/rsakey.h92
11 files changed, 1979 insertions, 0 deletions
diff --git a/crypto/akcipher-gcrypt.c.inc b/crypto/akcipher-gcrypt.c.inc
new file mode 100644
index 0000000..abb1fb2
--- /dev/null
+++ b/crypto/akcipher-gcrypt.c.inc
@@ -0,0 +1,595 @@
+/*
+ * QEMU Crypto akcipher algorithms
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include <gcrypt.h>
+
+#include "qemu/osdep.h"
+#include "qemu/host-utils.h"
+#include "crypto/akcipher.h"
+#include "crypto/random.h"
+#include "qapi/error.h"
+#include "sysemu/cryptodev.h"
+#include "rsakey.h"
+
+typedef struct QCryptoGcryptRSA {
+ QCryptoAkCipher akcipher;
+ gcry_sexp_t key;
+ QCryptoRSAPaddingAlgorithm padding_alg;
+ QCryptoHashAlgorithm hash_alg;
+} QCryptoGcryptRSA;
+
+static void qcrypto_gcrypt_rsa_free(QCryptoAkCipher *akcipher)
+{
+ QCryptoGcryptRSA *rsa = (QCryptoGcryptRSA *)akcipher;
+ if (!rsa) {
+ return;
+ }
+
+ gcry_sexp_release(rsa->key);
+ g_free(rsa);
+}
+
+static QCryptoGcryptRSA *qcrypto_gcrypt_rsa_new(
+ const QCryptoAkCipherOptionsRSA *opt,
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen,
+ Error **errp);
+
+QCryptoAkCipher *qcrypto_akcipher_new(const QCryptoAkCipherOptions *opts,
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen,
+ Error **errp)
+{
+ switch (opts->alg) {
+ case QCRYPTO_AKCIPHER_ALG_RSA:
+ return (QCryptoAkCipher *)qcrypto_gcrypt_rsa_new(
+ &opts->u.rsa, type, key, keylen, errp);
+
+ default:
+ error_setg(errp, "Unsupported algorithm: %u", opts->alg);
+ return NULL;
+ }
+
+ return NULL;
+}
+
+static void qcrypto_gcrypt_set_rsa_size(QCryptoAkCipher *akcipher, gcry_mpi_t n)
+{
+ size_t key_size = (gcry_mpi_get_nbits(n) + 7) / 8;
+ akcipher->max_plaintext_len = key_size;
+ akcipher->max_ciphertext_len = key_size;
+ akcipher->max_dgst_len = key_size;
+ akcipher->max_signature_len = key_size;
+}
+
+static int qcrypto_gcrypt_parse_rsa_private_key(
+ QCryptoGcryptRSA *rsa,
+ const uint8_t *key, size_t keylen, Error **errp)
+{
+ g_autoptr(QCryptoAkCipherRSAKey) rsa_key = qcrypto_akcipher_rsakey_parse(
+ QCRYPTO_AKCIPHER_KEY_TYPE_PRIVATE, key, keylen, errp);
+ gcry_mpi_t n = NULL, e = NULL, d = NULL, p = NULL, q = NULL, u = NULL;
+ bool compute_mul_inv = false;
+ int ret = -1;
+ gcry_error_t err;
+
+ if (!rsa_key) {
+ return ret;
+ }
+
+ err = gcry_mpi_scan(&n, GCRYMPI_FMT_STD,
+ rsa_key->n.data, rsa_key->n.len, NULL);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to parse RSA parameter n: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_mpi_scan(&e, GCRYMPI_FMT_STD,
+ rsa_key->e.data, rsa_key->e.len, NULL);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to parse RSA parameter e: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_mpi_scan(&d, GCRYMPI_FMT_STD,
+ rsa_key->d.data, rsa_key->d.len, NULL);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to parse RSA parameter d: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_mpi_scan(&p, GCRYMPI_FMT_STD,
+ rsa_key->p.data, rsa_key->p.len, NULL);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to parse RSA parameter p: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_mpi_scan(&q, GCRYMPI_FMT_STD,
+ rsa_key->q.data, rsa_key->q.len, NULL);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to parse RSA parameter q: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ if (gcry_mpi_cmp_ui(p, 0) > 0 && gcry_mpi_cmp_ui(q, 0) > 0) {
+ compute_mul_inv = true;
+
+ u = gcry_mpi_new(0);
+ if (gcry_mpi_cmp(p, q) > 0) {
+ gcry_mpi_swap(p, q);
+ }
+ gcry_mpi_invm(u, p, q);
+ }
+
+ if (compute_mul_inv) {
+ err = gcry_sexp_build(&rsa->key, NULL,
+ "(private-key (rsa (n %m) (e %m) (d %m) (p %m) (q %m) (u %m)))",
+ n, e, d, p, q, u);
+ } else {
+ err = gcry_sexp_build(&rsa->key, NULL,
+ "(private-key (rsa (n %m) (e %m) (d %m)))", n, e, d);
+ }
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to build RSA private key: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+ qcrypto_gcrypt_set_rsa_size((QCryptoAkCipher *)rsa, n);
+ ret = 0;
+
+cleanup:
+ gcry_mpi_release(n);
+ gcry_mpi_release(e);
+ gcry_mpi_release(d);
+ gcry_mpi_release(p);
+ gcry_mpi_release(q);
+ gcry_mpi_release(u);
+ return ret;
+}
+
+static int qcrypto_gcrypt_parse_rsa_public_key(QCryptoGcryptRSA *rsa,
+ const uint8_t *key,
+ size_t keylen,
+ Error **errp)
+{
+
+ g_autoptr(QCryptoAkCipherRSAKey) rsa_key = qcrypto_akcipher_rsakey_parse(
+ QCRYPTO_AKCIPHER_KEY_TYPE_PUBLIC, key, keylen, errp);
+ gcry_mpi_t n = NULL, e = NULL;
+ int ret = -1;
+ gcry_error_t err;
+
+ if (!rsa_key) {
+ return ret;
+ }
+
+ err = gcry_mpi_scan(&n, GCRYMPI_FMT_STD,
+ rsa_key->n.data, rsa_key->n.len, NULL);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to parse RSA parameter n: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_mpi_scan(&e, GCRYMPI_FMT_STD,
+ rsa_key->e.data, rsa_key->e.len, NULL);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to parse RSA parameter e: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_sexp_build(&rsa->key, NULL,
+ "(public-key (rsa (n %m) (e %m)))", n, e);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to build RSA public key: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+ qcrypto_gcrypt_set_rsa_size((QCryptoAkCipher *)rsa, n);
+ ret = 0;
+
+cleanup:
+ gcry_mpi_release(n);
+ gcry_mpi_release(e);
+ return ret;
+}
+
+static int qcrypto_gcrypt_rsa_encrypt(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len,
+ Error **errp)
+{
+ QCryptoGcryptRSA *rsa = (QCryptoGcryptRSA *)akcipher;
+ int ret = -1;
+ gcry_sexp_t data_sexp = NULL, cipher_sexp = NULL;
+ gcry_sexp_t cipher_sexp_item = NULL;
+ gcry_mpi_t cipher_mpi = NULL;
+ const char *result;
+ gcry_error_t err;
+ size_t actual_len;
+
+ if (in_len > akcipher->max_plaintext_len) {
+ error_setg(errp, "Plaintext length is greater than key size: %d",
+ akcipher->max_plaintext_len);
+ return ret;
+ }
+
+ err = gcry_sexp_build(&data_sexp, NULL,
+ "(data (flags %s) (value %b))",
+ QCryptoRSAPaddingAlgorithm_str(rsa->padding_alg),
+ in_len, in);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to build plaintext: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_pk_encrypt(&cipher_sexp, data_sexp, rsa->key);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to encrypt: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ /* S-expression of cipher: (enc-val (rsa (a a-mpi))) */
+ cipher_sexp_item = gcry_sexp_find_token(cipher_sexp, "a", 0);
+ if (!cipher_sexp_item || gcry_sexp_length(cipher_sexp_item) != 2) {
+ error_setg(errp, "Invalid ciphertext result");
+ goto cleanup;
+ }
+
+ if (rsa->padding_alg == QCRYPTO_RSA_PADDING_ALG_RAW) {
+ cipher_mpi = gcry_sexp_nth_mpi(cipher_sexp_item, 1, GCRYMPI_FMT_USG);
+ if (!cipher_mpi) {
+ error_setg(errp, "Invalid ciphertext result");
+ goto cleanup;
+ }
+ err = gcry_mpi_print(GCRYMPI_FMT_USG, out, out_len,
+ &actual_len, cipher_mpi);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to print MPI: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ if (actual_len > out_len) {
+ error_setg(errp, "Ciphertext buffer length is too small");
+ goto cleanup;
+ }
+
+ /* We always padding leading-zeros for RSA-RAW */
+ if (actual_len < out_len) {
+ memmove((uint8_t *)out + (out_len - actual_len), out, actual_len);
+ memset(out, 0, out_len - actual_len);
+ }
+ ret = out_len;
+
+ } else {
+ result = gcry_sexp_nth_data(cipher_sexp_item, 1, &actual_len);
+ if (!result) {
+ error_setg(errp, "Invalid ciphertext result");
+ goto cleanup;
+ }
+ if (actual_len > out_len) {
+ error_setg(errp, "Ciphertext buffer length is too small");
+ goto cleanup;
+ }
+ memcpy(out, result, actual_len);
+ ret = actual_len;
+ }
+
+cleanup:
+ gcry_sexp_release(data_sexp);
+ gcry_sexp_release(cipher_sexp);
+ gcry_sexp_release(cipher_sexp_item);
+ gcry_mpi_release(cipher_mpi);
+ return ret;
+}
+
+static int qcrypto_gcrypt_rsa_decrypt(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len,
+ Error **errp)
+{
+ QCryptoGcryptRSA *rsa = (QCryptoGcryptRSA *)akcipher;
+ int ret = -1;
+ gcry_sexp_t data_sexp = NULL, cipher_sexp = NULL;
+ gcry_mpi_t data_mpi = NULL;
+ gcry_error_t err;
+ size_t actual_len;
+ const char *result;
+
+ if (in_len > akcipher->max_ciphertext_len) {
+ error_setg(errp, "Ciphertext length is greater than key size: %d",
+ akcipher->max_ciphertext_len);
+ return ret;
+ }
+
+ err = gcry_sexp_build(&cipher_sexp, NULL,
+ "(enc-val (flags %s) (rsa (a %b) ))",
+ QCryptoRSAPaddingAlgorithm_str(rsa->padding_alg),
+ in_len, in);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to build ciphertext: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_pk_decrypt(&data_sexp, cipher_sexp, rsa->key);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to decrypt: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ /* S-expression of plaintext: (value plaintext) */
+ if (rsa->padding_alg == QCRYPTO_RSA_PADDING_ALG_RAW) {
+ data_mpi = gcry_sexp_nth_mpi(data_sexp, 1, GCRYMPI_FMT_USG);
+ if (!data_mpi) {
+ error_setg(errp, "Invalid plaintext result");
+ goto cleanup;
+ }
+ err = gcry_mpi_print(GCRYMPI_FMT_USG, out, out_len,
+ &actual_len, data_mpi);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to print MPI: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+ if (actual_len > out_len) {
+ error_setg(errp, "Plaintext buffer length is too small");
+ goto cleanup;
+ }
+ /* We always padding leading-zeros for RSA-RAW */
+ if (actual_len < out_len) {
+ memmove((uint8_t *)out + (out_len - actual_len), out, actual_len);
+ memset(out, 0, out_len - actual_len);
+ }
+ ret = out_len;
+ } else {
+ result = gcry_sexp_nth_data(data_sexp, 1, &actual_len);
+ if (!result) {
+ error_setg(errp, "Invalid plaintext result");
+ goto cleanup;
+ }
+ if (actual_len > out_len) {
+ error_setg(errp, "Plaintext buffer length is too small");
+ goto cleanup;
+ }
+ memcpy(out, result, actual_len);
+ ret = actual_len;
+ }
+
+cleanup:
+ gcry_sexp_release(cipher_sexp);
+ gcry_sexp_release(data_sexp);
+ gcry_mpi_release(data_mpi);
+ return ret;
+}
+
+static int qcrypto_gcrypt_rsa_sign(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len, Error **errp)
+{
+ QCryptoGcryptRSA *rsa = (QCryptoGcryptRSA *)akcipher;
+ int ret = -1;
+ gcry_sexp_t dgst_sexp = NULL, sig_sexp = NULL;
+ gcry_sexp_t sig_sexp_item = NULL;
+ const char *result;
+ gcry_error_t err;
+ size_t actual_len;
+
+ if (in_len > akcipher->max_dgst_len) {
+ error_setg(errp, "Data length is greater than key size: %d",
+ akcipher->max_dgst_len);
+ return ret;
+ }
+
+ if (rsa->padding_alg != QCRYPTO_RSA_PADDING_ALG_PKCS1) {
+ error_setg(errp, "Invalid padding %u", rsa->padding_alg);
+ return ret;
+ }
+
+ err = gcry_sexp_build(&dgst_sexp, NULL,
+ "(data (flags pkcs1) (hash %s %b))",
+ QCryptoHashAlgorithm_str(rsa->hash_alg),
+ in_len, in);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to build dgst: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_pk_sign(&sig_sexp, dgst_sexp, rsa->key);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to make signature: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ /* S-expression of signature: (sig-val (rsa (s s-mpi))) */
+ sig_sexp_item = gcry_sexp_find_token(sig_sexp, "s", 0);
+ if (!sig_sexp_item || gcry_sexp_length(sig_sexp_item) != 2) {
+ error_setg(errp, "Invalid signature result");
+ goto cleanup;
+ }
+
+ result = gcry_sexp_nth_data(sig_sexp_item, 1, &actual_len);
+ if (!result) {
+ error_setg(errp, "Invalid signature result");
+ goto cleanup;
+ }
+
+ if (actual_len > out_len) {
+ error_setg(errp, "Signature buffer length is too small");
+ goto cleanup;
+ }
+ memcpy(out, result, actual_len);
+ ret = actual_len;
+
+cleanup:
+ gcry_sexp_release(dgst_sexp);
+ gcry_sexp_release(sig_sexp);
+ gcry_sexp_release(sig_sexp_item);
+
+ return ret;
+}
+
+static int qcrypto_gcrypt_rsa_verify(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ const void *in2, size_t in2_len,
+ Error **errp)
+{
+ QCryptoGcryptRSA *rsa = (QCryptoGcryptRSA *)akcipher;
+ int ret = -1;
+ gcry_sexp_t sig_sexp = NULL, dgst_sexp = NULL;
+ gcry_error_t err;
+
+ if (in_len > akcipher->max_signature_len) {
+ error_setg(errp, "Signature length is greater than key size: %d",
+ akcipher->max_signature_len);
+ return ret;
+ }
+
+ if (in2_len > akcipher->max_dgst_len) {
+ error_setg(errp, "Data length is greater than key size: %d",
+ akcipher->max_dgst_len);
+ return ret;
+ }
+
+ if (rsa->padding_alg != QCRYPTO_RSA_PADDING_ALG_PKCS1) {
+ error_setg(errp, "Invalid padding %u", rsa->padding_alg);
+ return ret;
+ }
+
+ err = gcry_sexp_build(&sig_sexp, NULL,
+ "(sig-val (rsa (s %b)))", in_len, in);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to build signature: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_sexp_build(&dgst_sexp, NULL,
+ "(data (flags pkcs1) (hash %s %b))",
+ QCryptoHashAlgorithm_str(rsa->hash_alg),
+ in2_len, in2);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to build dgst: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+
+ err = gcry_pk_verify(sig_sexp, dgst_sexp, rsa->key);
+ if (gcry_err_code(err) != 0) {
+ error_setg(errp, "Failed to verify signature: %s/%s",
+ gcry_strsource(err), gcry_strerror(err));
+ goto cleanup;
+ }
+ ret = 0;
+
+cleanup:
+ gcry_sexp_release(dgst_sexp);
+ gcry_sexp_release(sig_sexp);
+
+ return ret;
+}
+
+QCryptoAkCipherDriver gcrypt_rsa = {
+ .encrypt = qcrypto_gcrypt_rsa_encrypt,
+ .decrypt = qcrypto_gcrypt_rsa_decrypt,
+ .sign = qcrypto_gcrypt_rsa_sign,
+ .verify = qcrypto_gcrypt_rsa_verify,
+ .free = qcrypto_gcrypt_rsa_free,
+};
+
+static QCryptoGcryptRSA *qcrypto_gcrypt_rsa_new(
+ const QCryptoAkCipherOptionsRSA *opt,
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen,
+ Error **errp)
+{
+ QCryptoGcryptRSA *rsa = g_new0(QCryptoGcryptRSA, 1);
+ rsa->padding_alg = opt->padding_alg;
+ rsa->hash_alg = opt->hash_alg;
+ rsa->akcipher.driver = &gcrypt_rsa;
+
+ switch (type) {
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PRIVATE:
+ if (qcrypto_gcrypt_parse_rsa_private_key(rsa, key, keylen, errp) != 0) {
+ goto error;
+ }
+ break;
+
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PUBLIC:
+ if (qcrypto_gcrypt_parse_rsa_public_key(rsa, key, keylen, errp) != 0) {
+ goto error;
+ }
+ break;
+
+ default:
+ error_setg(errp, "Unknown akcipher key type %d", type);
+ goto error;
+ }
+
+ return rsa;
+
+error:
+ qcrypto_gcrypt_rsa_free((QCryptoAkCipher *)rsa);
+ return NULL;
+}
+
+
+bool qcrypto_akcipher_supports(QCryptoAkCipherOptions *opts)
+{
+ switch (opts->alg) {
+ case QCRYPTO_AKCIPHER_ALG_RSA:
+ switch (opts->u.rsa.padding_alg) {
+ case QCRYPTO_RSA_PADDING_ALG_RAW:
+ return true;
+
+ case QCRYPTO_RSA_PADDING_ALG_PKCS1:
+ switch (opts->u.rsa.hash_alg) {
+ case QCRYPTO_HASH_ALG_MD5:
+ case QCRYPTO_HASH_ALG_SHA1:
+ case QCRYPTO_HASH_ALG_SHA256:
+ case QCRYPTO_HASH_ALG_SHA512:
+ return true;
+
+ default:
+ return false;
+ }
+
+ default:
+ return false;
+ }
+
+ default:
+ return true;
+ }
+}
diff --git a/crypto/akcipher-nettle.c.inc b/crypto/akcipher-nettle.c.inc
new file mode 100644
index 0000000..02699e6
--- /dev/null
+++ b/crypto/akcipher-nettle.c.inc
@@ -0,0 +1,451 @@
+/*
+ * QEMU Crypto akcipher algorithms
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include <nettle/rsa.h>
+
+#include "qemu/osdep.h"
+#include "qemu/host-utils.h"
+#include "crypto/akcipher.h"
+#include "crypto/random.h"
+#include "qapi/error.h"
+#include "sysemu/cryptodev.h"
+#include "rsakey.h"
+
+typedef struct QCryptoNettleRSA {
+ QCryptoAkCipher akcipher;
+ struct rsa_public_key pub;
+ struct rsa_private_key priv;
+ QCryptoRSAPaddingAlgorithm padding_alg;
+ QCryptoHashAlgorithm hash_alg;
+} QCryptoNettleRSA;
+
+static void qcrypto_nettle_rsa_free(QCryptoAkCipher *akcipher)
+{
+ QCryptoNettleRSA *rsa = (QCryptoNettleRSA *)akcipher;
+ if (!rsa) {
+ return;
+ }
+
+ rsa_public_key_clear(&rsa->pub);
+ rsa_private_key_clear(&rsa->priv);
+ g_free(rsa);
+}
+
+static QCryptoAkCipher *qcrypto_nettle_rsa_new(
+ const QCryptoAkCipherOptionsRSA *opt,
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen,
+ Error **errp);
+
+QCryptoAkCipher *qcrypto_akcipher_new(const QCryptoAkCipherOptions *opts,
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen,
+ Error **errp)
+{
+ switch (opts->alg) {
+ case QCRYPTO_AKCIPHER_ALG_RSA:
+ return qcrypto_nettle_rsa_new(&opts->u.rsa, type, key, keylen, errp);
+
+ default:
+ error_setg(errp, "Unsupported algorithm: %u", opts->alg);
+ return NULL;
+ }
+
+ return NULL;
+}
+
+static void qcrypto_nettle_rsa_set_akcipher_size(QCryptoAkCipher *akcipher,
+ int key_size)
+{
+ akcipher->max_plaintext_len = key_size;
+ akcipher->max_ciphertext_len = key_size;
+ akcipher->max_signature_len = key_size;
+ akcipher->max_dgst_len = key_size;
+}
+
+static int qcrypt_nettle_parse_rsa_private_key(QCryptoNettleRSA *rsa,
+ const uint8_t *key,
+ size_t keylen,
+ Error **errp)
+{
+ g_autoptr(QCryptoAkCipherRSAKey) rsa_key = qcrypto_akcipher_rsakey_parse(
+ QCRYPTO_AKCIPHER_KEY_TYPE_PRIVATE, key, keylen, errp);
+
+ if (!rsa_key) {
+ return -1;
+ }
+
+ nettle_mpz_init_set_str_256_u(rsa->pub.n, rsa_key->n.len, rsa_key->n.data);
+ nettle_mpz_init_set_str_256_u(rsa->pub.e, rsa_key->e.len, rsa_key->e.data);
+ nettle_mpz_init_set_str_256_u(rsa->priv.d, rsa_key->d.len, rsa_key->d.data);
+ nettle_mpz_init_set_str_256_u(rsa->priv.p, rsa_key->p.len, rsa_key->p.data);
+ nettle_mpz_init_set_str_256_u(rsa->priv.q, rsa_key->q.len, rsa_key->q.data);
+ nettle_mpz_init_set_str_256_u(rsa->priv.a, rsa_key->dp.len,
+ rsa_key->dp.data);
+ nettle_mpz_init_set_str_256_u(rsa->priv.b, rsa_key->dq.len,
+ rsa_key->dq.data);
+ nettle_mpz_init_set_str_256_u(rsa->priv.c, rsa_key->u.len, rsa_key->u.data);
+
+ if (!rsa_public_key_prepare(&rsa->pub)) {
+ error_setg(errp, "Failed to check RSA key");
+ return -1;
+ }
+
+ /**
+ * Since in the kernel's unit test, the p, q, a, b, c of some
+ * private keys is 0, only the simplest length check is done here
+ */
+ if (rsa_key->p.len > 1 &&
+ rsa_key->q.len > 1 &&
+ rsa_key->dp.len > 1 &&
+ rsa_key->dq.len > 1 &&
+ rsa_key->u.len > 1) {
+ if (!rsa_private_key_prepare(&rsa->priv)) {
+ error_setg(errp, "Failed to check RSA key");
+ return -1;
+ }
+ } else {
+ rsa->priv.size = rsa->pub.size;
+ }
+ qcrypto_nettle_rsa_set_akcipher_size(
+ (QCryptoAkCipher *)rsa, rsa->priv.size);
+
+ return 0;
+}
+
+static int qcrypt_nettle_parse_rsa_public_key(QCryptoNettleRSA *rsa,
+ const uint8_t *key,
+ size_t keylen,
+ Error **errp)
+{
+ g_autoptr(QCryptoAkCipherRSAKey) rsa_key = qcrypto_akcipher_rsakey_parse(
+ QCRYPTO_AKCIPHER_KEY_TYPE_PUBLIC, key, keylen, errp);
+
+ if (!rsa_key) {
+ return -1;
+ }
+ nettle_mpz_init_set_str_256_u(rsa->pub.n, rsa_key->n.len, rsa_key->n.data);
+ nettle_mpz_init_set_str_256_u(rsa->pub.e, rsa_key->e.len, rsa_key->e.data);
+
+ if (!rsa_public_key_prepare(&rsa->pub)) {
+ error_setg(errp, "Failed to check RSA key");
+ return -1;
+ }
+ qcrypto_nettle_rsa_set_akcipher_size(
+ (QCryptoAkCipher *)rsa, rsa->pub.size);
+
+ return 0;
+}
+
+static void wrap_nettle_random_func(void *ctx, size_t len, uint8_t *out)
+{
+ qcrypto_random_bytes(out, len, &error_abort);
+}
+
+static int qcrypto_nettle_rsa_encrypt(QCryptoAkCipher *akcipher,
+ const void *data, size_t data_len,
+ void *enc, size_t enc_len,
+ Error **errp)
+{
+
+ QCryptoNettleRSA *rsa = (QCryptoNettleRSA *)akcipher;
+ mpz_t c;
+ int ret = -1;
+
+ if (data_len > rsa->pub.size) {
+ error_setg(errp, "Plaintext length %zu is greater than key size: %zu",
+ data_len, rsa->pub.size);
+ return ret;
+ }
+
+ if (enc_len < rsa->pub.size) {
+ error_setg(errp, "Ciphertext buffer length %zu is less than "
+ "key size: %zu", enc_len, rsa->pub.size);
+ return ret;
+ }
+
+ /* Nettle do not support RSA encryption without any padding */
+ switch (rsa->padding_alg) {
+ case QCRYPTO_RSA_PADDING_ALG_RAW:
+ error_setg(errp, "RSA with raw padding is not supported");
+ break;
+
+ case QCRYPTO_RSA_PADDING_ALG_PKCS1:
+ mpz_init(c);
+ if (rsa_encrypt(&rsa->pub, NULL, wrap_nettle_random_func,
+ data_len, (uint8_t *)data, c) != 1) {
+ error_setg(errp, "Failed to encrypt");
+ } else {
+ nettle_mpz_get_str_256(enc_len, (uint8_t *)enc, c);
+ ret = nettle_mpz_sizeinbase_256_u(c);
+ }
+ mpz_clear(c);
+ break;
+
+ default:
+ error_setg(errp, "Unknown padding");
+ }
+
+ return ret;
+}
+
+static int qcrypto_nettle_rsa_decrypt(QCryptoAkCipher *akcipher,
+ const void *enc, size_t enc_len,
+ void *data, size_t data_len,
+ Error **errp)
+{
+ QCryptoNettleRSA *rsa = (QCryptoNettleRSA *)akcipher;
+ mpz_t c;
+ int ret = -1;
+
+ if (enc_len > rsa->priv.size) {
+ error_setg(errp, "Ciphertext length %zu is greater than key size: %zu",
+ enc_len, rsa->priv.size);
+ return ret;
+ }
+
+ switch (rsa->padding_alg) {
+ case QCRYPTO_RSA_PADDING_ALG_RAW:
+ error_setg(errp, "RSA with raw padding is not supported");
+ break;
+
+ case QCRYPTO_RSA_PADDING_ALG_PKCS1:
+ nettle_mpz_init_set_str_256_u(c, enc_len, enc);
+ if (!rsa_decrypt(&rsa->priv, &data_len, (uint8_t *)data, c)) {
+ error_setg(errp, "Failed to decrypt");
+ } else {
+ ret = data_len;
+ }
+
+ mpz_clear(c);
+ break;
+
+ default:
+ error_setg(errp, "Unknown padding algorithm: %d", rsa->padding_alg);
+ }
+
+ return ret;
+}
+
+static int qcrypto_nettle_rsa_sign(QCryptoAkCipher *akcipher,
+ const void *data, size_t data_len,
+ void *sig, size_t sig_len, Error **errp)
+{
+ QCryptoNettleRSA *rsa = (QCryptoNettleRSA *)akcipher;
+ int ret = -1, rv;
+ mpz_t s;
+
+ /**
+ * The RSA algorithm cannot be used for signature/verification
+ * without padding.
+ */
+ if (rsa->padding_alg == QCRYPTO_RSA_PADDING_ALG_RAW) {
+ error_setg(errp, "Try to make signature without padding");
+ return ret;
+ }
+
+ if (data_len > rsa->priv.size) {
+ error_setg(errp, "Data length %zu is greater than key size: %zu",
+ data_len, rsa->priv.size);
+ return ret;
+ }
+
+ if (sig_len < rsa->priv.size) {
+ error_setg(errp, "Signature buffer length %zu is less than "
+ "key size: %zu", sig_len, rsa->priv.size);
+ return ret;
+ }
+
+ mpz_init(s);
+ switch (rsa->hash_alg) {
+ case QCRYPTO_HASH_ALG_MD5:
+ rv = rsa_md5_sign_digest(&rsa->priv, data, s);
+ break;
+
+ case QCRYPTO_HASH_ALG_SHA1:
+ rv = rsa_sha1_sign_digest(&rsa->priv, data, s);
+ break;
+
+ case QCRYPTO_HASH_ALG_SHA256:
+ rv = rsa_sha256_sign_digest(&rsa->priv, data, s);
+ break;
+
+ case QCRYPTO_HASH_ALG_SHA512:
+ rv = rsa_sha512_sign_digest(&rsa->priv, data, s);
+ break;
+
+ default:
+ error_setg(errp, "Unknown hash algorithm: %d", rsa->hash_alg);
+ goto cleanup;
+ }
+
+ if (rv != 1) {
+ error_setg(errp, "Failed to make signature");
+ goto cleanup;
+ }
+ nettle_mpz_get_str_256(sig_len, (uint8_t *)sig, s);
+ ret = nettle_mpz_sizeinbase_256_u(s);
+
+cleanup:
+ mpz_clear(s);
+
+ return ret;
+}
+
+static int qcrypto_nettle_rsa_verify(QCryptoAkCipher *akcipher,
+ const void *sig, size_t sig_len,
+ const void *data, size_t data_len,
+ Error **errp)
+{
+ QCryptoNettleRSA *rsa = (QCryptoNettleRSA *)akcipher;
+
+ int ret = -1, rv;
+ mpz_t s;
+
+ /**
+ * The RSA algorithm cannot be used for signature/verification
+ * without padding.
+ */
+ if (rsa->padding_alg == QCRYPTO_RSA_PADDING_ALG_RAW) {
+ error_setg(errp, "Try to verify signature without padding");
+ return ret;
+ }
+ if (data_len > rsa->pub.size) {
+ error_setg(errp, "Data length %zu is greater than key size: %zu",
+ data_len, rsa->pub.size);
+ return ret;
+ }
+ if (sig_len < rsa->pub.size) {
+ error_setg(errp, "Signature length %zu is greater than key size: %zu",
+ sig_len, rsa->pub.size);
+ return ret;
+ }
+
+ nettle_mpz_init_set_str_256_u(s, sig_len, sig);
+ switch (rsa->hash_alg) {
+ case QCRYPTO_HASH_ALG_MD5:
+ rv = rsa_md5_verify_digest(&rsa->pub, data, s);
+ break;
+
+ case QCRYPTO_HASH_ALG_SHA1:
+ rv = rsa_sha1_verify_digest(&rsa->pub, data, s);
+ break;
+
+ case QCRYPTO_HASH_ALG_SHA256:
+ rv = rsa_sha256_verify_digest(&rsa->pub, data, s);
+ break;
+
+ case QCRYPTO_HASH_ALG_SHA512:
+ rv = rsa_sha512_verify_digest(&rsa->pub, data, s);
+ break;
+
+ default:
+ error_setg(errp, "Unsupported hash algorithm: %d", rsa->hash_alg);
+ goto cleanup;
+ }
+
+ if (rv != 1) {
+ error_setg(errp, "Failed to verify signature");
+ goto cleanup;
+ }
+ ret = 0;
+
+cleanup:
+ mpz_clear(s);
+
+ return ret;
+}
+
+QCryptoAkCipherDriver nettle_rsa = {
+ .encrypt = qcrypto_nettle_rsa_encrypt,
+ .decrypt = qcrypto_nettle_rsa_decrypt,
+ .sign = qcrypto_nettle_rsa_sign,
+ .verify = qcrypto_nettle_rsa_verify,
+ .free = qcrypto_nettle_rsa_free,
+};
+
+static QCryptoAkCipher *qcrypto_nettle_rsa_new(
+ const QCryptoAkCipherOptionsRSA *opt,
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen,
+ Error **errp)
+{
+ QCryptoNettleRSA *rsa = g_new0(QCryptoNettleRSA, 1);
+
+ rsa->padding_alg = opt->padding_alg;
+ rsa->hash_alg = opt->hash_alg;
+ rsa->akcipher.driver = &nettle_rsa;
+ rsa_public_key_init(&rsa->pub);
+ rsa_private_key_init(&rsa->priv);
+
+ switch (type) {
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PRIVATE:
+ if (qcrypt_nettle_parse_rsa_private_key(rsa, key, keylen, errp) != 0) {
+ goto error;
+ }
+ break;
+
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PUBLIC:
+ if (qcrypt_nettle_parse_rsa_public_key(rsa, key, keylen, errp) != 0) {
+ goto error;
+ }
+ break;
+
+ default:
+ error_setg(errp, "Unknown akcipher key type %d", type);
+ goto error;
+ }
+
+ return (QCryptoAkCipher *)rsa;
+
+error:
+ qcrypto_nettle_rsa_free((QCryptoAkCipher *)rsa);
+ return NULL;
+}
+
+
+bool qcrypto_akcipher_supports(QCryptoAkCipherOptions *opts)
+{
+ switch (opts->alg) {
+ case QCRYPTO_AKCIPHER_ALG_RSA:
+ switch (opts->u.rsa.padding_alg) {
+ case QCRYPTO_RSA_PADDING_ALG_PKCS1:
+ switch (opts->u.rsa.hash_alg) {
+ case QCRYPTO_HASH_ALG_MD5:
+ case QCRYPTO_HASH_ALG_SHA1:
+ case QCRYPTO_HASH_ALG_SHA256:
+ case QCRYPTO_HASH_ALG_SHA512:
+ return true;
+
+ default:
+ return false;
+ }
+
+ case QCRYPTO_RSA_PADDING_ALG_RAW:
+ default:
+ return false;
+ }
+ break;
+
+ default:
+ return false;
+ }
+}
diff --git a/crypto/akcipher.c b/crypto/akcipher.c
new file mode 100644
index 0000000..ad88379
--- /dev/null
+++ b/crypto/akcipher.c
@@ -0,0 +1,108 @@
+/*
+ * QEMU Crypto akcipher algorithms
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: zhenwei pi <pizhenwei@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "qemu/osdep.h"
+#include "crypto/akcipher.h"
+#include "akcipherpriv.h"
+
+#if defined(CONFIG_GCRYPT)
+#include "akcipher-gcrypt.c.inc"
+#elif defined(CONFIG_NETTLE) && defined(CONFIG_HOGWEED)
+#include "akcipher-nettle.c.inc"
+#else
+QCryptoAkCipher *qcrypto_akcipher_new(const QCryptoAkCipherOptions *opts,
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen,
+ Error **errp)
+{
+ QCryptoAkCipher *akcipher = NULL;
+
+ return akcipher;
+}
+
+bool qcrypto_akcipher_supports(QCryptoAkCipherOptions *opts)
+{
+ return false;
+}
+#endif
+
+int qcrypto_akcipher_encrypt(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len, Error **errp)
+{
+ const QCryptoAkCipherDriver *drv = akcipher->driver;
+
+ return drv->encrypt(akcipher, in, in_len, out, out_len, errp);
+}
+
+int qcrypto_akcipher_decrypt(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len, Error **errp)
+{
+ const QCryptoAkCipherDriver *drv = akcipher->driver;
+
+ return drv->decrypt(akcipher, in, in_len, out, out_len, errp);
+}
+
+int qcrypto_akcipher_sign(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len, Error **errp)
+{
+ const QCryptoAkCipherDriver *drv = akcipher->driver;
+
+ return drv->sign(akcipher, in, in_len, out, out_len, errp);
+}
+
+int qcrypto_akcipher_verify(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ const void *in2, size_t in2_len, Error **errp)
+{
+ const QCryptoAkCipherDriver *drv = akcipher->driver;
+
+ return drv->verify(akcipher, in, in_len, in2, in2_len, errp);
+}
+
+int qcrypto_akcipher_max_plaintext_len(QCryptoAkCipher *akcipher)
+{
+ return akcipher->max_plaintext_len;
+}
+
+int qcrypto_akcipher_max_ciphertext_len(QCryptoAkCipher *akcipher)
+{
+ return akcipher->max_ciphertext_len;
+}
+
+int qcrypto_akcipher_max_signature_len(QCryptoAkCipher *akcipher)
+{
+ return akcipher->max_signature_len;
+}
+
+int qcrypto_akcipher_max_dgst_len(QCryptoAkCipher *akcipher)
+{
+ return akcipher->max_dgst_len;
+}
+
+void qcrypto_akcipher_free(QCryptoAkCipher *akcipher)
+{
+ const QCryptoAkCipherDriver *drv = akcipher->driver;
+
+ drv->free(akcipher);
+}
diff --git a/crypto/akcipherpriv.h b/crypto/akcipherpriv.h
new file mode 100644
index 0000000..739f639
--- /dev/null
+++ b/crypto/akcipherpriv.h
@@ -0,0 +1,55 @@
+/*
+ * QEMU Crypto asymmetric algorithms
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: zhenwei pi <pizhenwei@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef QCRYPTO_AKCIPHERPRIV_H
+#define QCRYPTO_AKCIPHERPRIV_H
+
+#include "qapi/qapi-types-crypto.h"
+
+typedef struct QCryptoAkCipherDriver QCryptoAkCipherDriver;
+
+struct QCryptoAkCipher {
+ QCryptoAkCipherAlgorithm alg;
+ QCryptoAkCipherKeyType type;
+ int max_plaintext_len;
+ int max_ciphertext_len;
+ int max_signature_len;
+ int max_dgst_len;
+ QCryptoAkCipherDriver *driver;
+};
+
+struct QCryptoAkCipherDriver {
+ int (*encrypt)(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len, Error **errp);
+ int (*decrypt)(QCryptoAkCipher *akcipher,
+ const void *out, size_t out_len,
+ void *in, size_t in_len, Error **errp);
+ int (*sign)(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ void *out, size_t out_len, Error **errp);
+ int (*verify)(QCryptoAkCipher *akcipher,
+ const void *in, size_t in_len,
+ const void *in2, size_t in2_len, Error **errp);
+ void (*free)(QCryptoAkCipher *akcipher);
+};
+
+#endif /* QCRYPTO_AKCIPHER_H */
diff --git a/crypto/der.c b/crypto/der.c
new file mode 100644
index 0000000..f877390
--- /dev/null
+++ b/crypto/der.c
@@ -0,0 +1,189 @@
+/*
+ * QEMU Crypto ASN.1 DER decoder
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "qemu/osdep.h"
+#include "crypto/der.h"
+
+enum QCryptoDERTypeTag {
+ QCRYPTO_DER_TYPE_TAG_BOOL = 0x1,
+ QCRYPTO_DER_TYPE_TAG_INT = 0x2,
+ QCRYPTO_DER_TYPE_TAG_BIT_STR = 0x3,
+ QCRYPTO_DER_TYPE_TAG_OCT_STR = 0x4,
+ QCRYPTO_DER_TYPE_TAG_OCT_NULL = 0x5,
+ QCRYPTO_DER_TYPE_TAG_OCT_OID = 0x6,
+ QCRYPTO_DER_TYPE_TAG_SEQ = 0x10,
+ QCRYPTO_DER_TYPE_TAG_SET = 0x11,
+};
+
+#define QCRYPTO_DER_CONSTRUCTED_MASK 0x20
+#define QCRYPTO_DER_SHORT_LEN_MASK 0x80
+
+static uint8_t qcrypto_der_peek_byte(const uint8_t **data, size_t *dlen)
+{
+ return **data;
+}
+
+static void qcrypto_der_cut_nbytes(const uint8_t **data,
+ size_t *dlen,
+ size_t nbytes)
+{
+ *data += nbytes;
+ *dlen -= nbytes;
+}
+
+static uint8_t qcrypto_der_cut_byte(const uint8_t **data, size_t *dlen)
+{
+ uint8_t val = qcrypto_der_peek_byte(data, dlen);
+
+ qcrypto_der_cut_nbytes(data, dlen, 1);
+
+ return val;
+}
+
+static int qcrypto_der_invoke_callback(QCryptoDERDecodeCb cb, void *ctx,
+ const uint8_t *value, size_t vlen,
+ Error **errp)
+{
+ if (!cb) {
+ return 0;
+ }
+
+ return cb(ctx, value, vlen, errp);
+}
+
+static int qcrypto_der_extract_definite_data(const uint8_t **data, size_t *dlen,
+ QCryptoDERDecodeCb cb, void *ctx,
+ Error **errp)
+{
+ const uint8_t *value;
+ size_t vlen = 0;
+ uint8_t byte_count = qcrypto_der_cut_byte(data, dlen);
+
+ /* short format of definite-length */
+ if (!(byte_count & QCRYPTO_DER_SHORT_LEN_MASK)) {
+ if (byte_count > *dlen) {
+ error_setg(errp, "Invalid content length: %u", byte_count);
+ return -1;
+ }
+
+ value = *data;
+ vlen = byte_count;
+ qcrypto_der_cut_nbytes(data, dlen, vlen);
+
+ if (qcrypto_der_invoke_callback(cb, ctx, value, vlen, errp) != 0) {
+ return -1;
+ }
+ return vlen;
+ }
+
+ /* Ignore highest bit */
+ byte_count &= ~QCRYPTO_DER_SHORT_LEN_MASK;
+
+ /*
+ * size_t is enough to store the value of length, although the DER
+ * encoding standard supports larger length.
+ */
+ if (byte_count > sizeof(size_t)) {
+ error_setg(errp, "Invalid byte count of content length: %u",
+ byte_count);
+ return -1;
+ }
+
+ if (byte_count > *dlen) {
+ error_setg(errp, "Invalid content length: %u", byte_count);
+ return -1;
+ }
+ while (byte_count--) {
+ vlen <<= 8;
+ vlen += qcrypto_der_cut_byte(data, dlen);
+ }
+
+ if (vlen > *dlen) {
+ error_setg(errp, "Invalid content length: %zu", vlen);
+ return -1;
+ }
+
+ value = *data;
+ qcrypto_der_cut_nbytes(data, dlen, vlen);
+
+ if (qcrypto_der_invoke_callback(cb, ctx, value, vlen, errp) != 0) {
+ return -1;
+ }
+ return vlen;
+}
+
+static int qcrypto_der_extract_data(const uint8_t **data, size_t *dlen,
+ QCryptoDERDecodeCb cb, void *ctx,
+ Error **errp)
+{
+ uint8_t val;
+ if (*dlen < 1) {
+ error_setg(errp, "Need more data");
+ return -1;
+ }
+ val = qcrypto_der_peek_byte(data, dlen);
+
+ /* must use definite length format */
+ if (val == QCRYPTO_DER_SHORT_LEN_MASK) {
+ error_setg(errp, "Only definite length format is allowed");
+ return -1;
+ }
+
+ return qcrypto_der_extract_definite_data(data, dlen, cb, ctx, errp);
+}
+
+int qcrypto_der_decode_int(const uint8_t **data, size_t *dlen,
+ QCryptoDERDecodeCb cb, void *ctx, Error **errp)
+{
+ uint8_t tag;
+ if (*dlen < 1) {
+ error_setg(errp, "Need more data");
+ return -1;
+ }
+ tag = qcrypto_der_cut_byte(data, dlen);
+
+ /* INTEGER must encoded in primitive-form */
+ if (tag != QCRYPTO_DER_TYPE_TAG_INT) {
+ error_setg(errp, "Invalid integer type tag: %u", tag);
+ return -1;
+ }
+
+ return qcrypto_der_extract_data(data, dlen, cb, ctx, errp);
+}
+
+int qcrypto_der_decode_seq(const uint8_t **data, size_t *dlen,
+ QCryptoDERDecodeCb cb, void *ctx, Error **errp)
+{
+ uint8_t tag;
+ if (*dlen < 1) {
+ error_setg(errp, "Need more data");
+ return -1;
+ }
+ tag = qcrypto_der_cut_byte(data, dlen);
+
+ /* SEQUENCE must use constructed form */
+ if (tag != (QCRYPTO_DER_TYPE_TAG_SEQ | QCRYPTO_DER_CONSTRUCTED_MASK)) {
+ error_setg(errp, "Invalid type sequence tag: %u", tag);
+ return -1;
+ }
+
+ return qcrypto_der_extract_data(data, dlen, cb, ctx, errp);
+}
diff --git a/crypto/der.h b/crypto/der.h
new file mode 100644
index 0000000..e3d3aea
--- /dev/null
+++ b/crypto/der.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef QCRYPTO_ASN1_DECODER_H
+#define QCRYPTO_ASN1_DECODER_H
+
+#include "qapi/error.h"
+
+/* Simple decoder used to parse DER encoded rsa keys. */
+
+/**
+ * @opaque: user context.
+ * @value: the starting address of |value| part of 'Tag-Length-Value' pattern.
+ * @vlen: length of the |value|.
+ * Returns: 0 for success, any other value is considered an error.
+ */
+typedef int (*QCryptoDERDecodeCb) (void *opaque, const uint8_t *value,
+ size_t vlen, Error **errp);
+
+/**
+ * qcrypto_der_decode_int:
+ * @data: pointer to address of input data
+ * @dlen: pointer to length of input data
+ * @cb: callback invoked when decode succeed, if cb equals NULL, no
+ * callback will be invoked
+ * @opaque: parameter passed to cb
+ *
+ * Decode integer from DER-encoded data.
+ *
+ * Returns: On success, *data points to rest data, and *dlen
+ * will be set to the rest length of data, if cb is not NULL, must
+ * return 0 to make decode success, at last, the length of the data
+ * part of the decoded INTEGER will be returned. Otherwise, -1 is
+ * returned.
+ */
+int qcrypto_der_decode_int(const uint8_t **data,
+ size_t *dlen,
+ QCryptoDERDecodeCb cb,
+ void *opaque,
+ Error **errp);
+
+/**
+ * qcrypto_der_decode_seq:
+ *
+ * Decode sequence from DER-encoded data, similar with der_decode_int.
+ *
+ * @data: pointer to address of input data
+ * @dlen: pointer to length of input data
+ * @cb: callback invoked when decode succeed, if cb equals NULL, no
+ * callback will be invoked
+ * @opaque: parameter passed to cb
+ *
+ * Returns: On success, *data points to rest data, and *dlen
+ * will be set to the rest length of data, if cb is not NULL, must
+ * return 0 to make decode success, at last, the length of the data
+ * part of the decoded SEQUENCE will be returned. Otherwise, -1 is
+ * returned.
+ */
+int qcrypto_der_decode_seq(const uint8_t **data,
+ size_t *dlen,
+ QCryptoDERDecodeCb cb,
+ void *opaque,
+ Error **errp);
+
+#endif /* QCRYPTO_ASN1_DECODER_H */
diff --git a/crypto/meson.build b/crypto/meson.build
index 685fb37..5f03a30 100644
--- a/crypto/meson.build
+++ b/crypto/meson.build
@@ -1,10 +1,12 @@
crypto_ss.add(genh)
crypto_ss.add(files(
'afsplit.c',
+ 'akcipher.c',
'block-luks.c',
'block-qcow.c',
'block.c',
'cipher.c',
+ 'der.c',
'hash.c',
'hmac.c',
'ivgen-essiv.c',
@@ -19,10 +21,14 @@ crypto_ss.add(files(
'tlscredspsk.c',
'tlscredsx509.c',
'tlssession.c',
+ 'rsakey.c',
))
if nettle.found()
crypto_ss.add(nettle, files('hash-nettle.c', 'hmac-nettle.c', 'pbkdf-nettle.c'))
+ if hogweed.found()
+ crypto_ss.add(gmp, hogweed)
+ endif
if xts == 'private'
crypto_ss.add(files('xts.c'))
endif
diff --git a/crypto/rsakey-builtin.c.inc b/crypto/rsakey-builtin.c.inc
new file mode 100644
index 0000000..aeeacc8
--- /dev/null
+++ b/crypto/rsakey-builtin.c.inc
@@ -0,0 +1,200 @@
+/*
+ * QEMU Crypto akcipher algorithms
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "der.h"
+#include "rsakey.h"
+
+static int extract_mpi(void *ctx, const uint8_t *value,
+ size_t vlen, Error **errp)
+{
+ QCryptoAkCipherMPI *mpi = (QCryptoAkCipherMPI *)ctx;
+ if (vlen == 0) {
+ error_setg(errp, "Empty mpi field");
+ return -1;
+ }
+ mpi->data = g_memdup2(value, vlen);
+ mpi->len = vlen;
+ return 0;
+}
+
+static int extract_version(void *ctx, const uint8_t *value,
+ size_t vlen, Error **errp)
+{
+ uint8_t *version = (uint8_t *)ctx;
+ if (vlen != 1 || *value > 1) {
+ error_setg(errp, "Invalid rsakey version");
+ return -1;
+ }
+ *version = *value;
+ return 0;
+}
+
+static int extract_seq_content(void *ctx, const uint8_t *value,
+ size_t vlen, Error **errp)
+{
+ const uint8_t **content = (const uint8_t **)ctx;
+ if (vlen == 0) {
+ error_setg(errp, "Empty sequence");
+ return -1;
+ }
+ *content = value;
+ return 0;
+}
+
+/**
+ *
+ * RsaPubKey ::= SEQUENCE {
+ * n INTEGER
+ * e INTEGER
+ * }
+ */
+static QCryptoAkCipherRSAKey *qcrypto_builtin_rsa_public_key_parse(
+ const uint8_t *key, size_t keylen, Error **errp)
+{
+ QCryptoAkCipherRSAKey *rsa = g_new0(QCryptoAkCipherRSAKey, 1);
+ const uint8_t *seq;
+ size_t seq_length;
+ int decode_ret;
+
+ decode_ret = qcrypto_der_decode_seq(&key, &keylen,
+ extract_seq_content, &seq, errp);
+ if (decode_ret < 0 || keylen != 0) {
+ goto error;
+ }
+ seq_length = decode_ret;
+
+ if (qcrypto_der_decode_int(&seq, &seq_length, extract_mpi,
+ &rsa->n, errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi,
+ &rsa->e, errp) < 0) {
+ goto error;
+ }
+ if (seq_length != 0) {
+ goto error;
+ }
+
+ return rsa;
+
+error:
+ if (errp && !*errp) {
+ error_setg(errp, "Invalid RSA public key");
+ }
+ qcrypto_akcipher_rsakey_free(rsa);
+ return NULL;
+}
+
+/**
+ * RsaPrivKey ::= SEQUENCE {
+ * version INTEGER
+ * n INTEGER
+ * e INTEGER
+ * d INTEGER
+ * p INTEGER
+ * q INTEGER
+ * dp INTEGER
+ * dq INTEGER
+ * u INTEGER
+ * otherPrimeInfos OtherPrimeInfos OPTIONAL
+ * }
+ */
+static QCryptoAkCipherRSAKey *qcrypto_builtin_rsa_private_key_parse(
+ const uint8_t *key, size_t keylen, Error **errp)
+{
+ QCryptoAkCipherRSAKey *rsa = g_new0(QCryptoAkCipherRSAKey, 1);
+ uint8_t version;
+ const uint8_t *seq;
+ int decode_ret;
+ size_t seq_length;
+
+ decode_ret = qcrypto_der_decode_seq(&key, &keylen, extract_seq_content,
+ &seq, errp);
+ if (decode_ret < 0 || keylen != 0) {
+ goto error;
+ }
+ seq_length = decode_ret;
+
+ decode_ret = qcrypto_der_decode_int(&seq, &seq_length, extract_version,
+ &version, errp);
+
+ if (qcrypto_der_decode_int(&seq, &seq_length, extract_mpi,
+ &rsa->n, errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi,
+ &rsa->e, errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi,
+ &rsa->d, errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi, &rsa->p,
+ errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi, &rsa->q,
+ errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi, &rsa->dp,
+ errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi, &rsa->dq,
+ errp) < 0 ||
+ qcrypto_der_decode_int(&seq, &seq_length, extract_mpi, &rsa->u,
+ errp) < 0) {
+ goto error;
+ }
+
+ /**
+ * According to the standard, otherPrimeInfos must be present for version 1.
+ * There is no strict verification here, this is to be compatible with
+ * the unit test of the kernel. TODO: remove this until linux kernel's
+ * unit-test is fixed.
+ */
+ if (version == 1 && seq_length != 0) {
+ if (qcrypto_der_decode_seq(&seq, &seq_length, NULL, NULL, errp) < 0) {
+ goto error;
+ }
+ if (seq_length != 0) {
+ goto error;
+ }
+ return rsa;
+ }
+ if (seq_length != 0) {
+ goto error;
+ }
+
+ return rsa;
+
+error:
+ if (errp && !*errp) {
+ error_setg(errp, "Invalid RSA private key");
+ }
+ qcrypto_akcipher_rsakey_free(rsa);
+ return NULL;
+}
+
+QCryptoAkCipherRSAKey *qcrypto_akcipher_rsakey_parse(
+ QCryptoAkCipherKeyType type, const uint8_t *key,
+ size_t keylen, Error **errp)
+{
+ switch (type) {
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PRIVATE:
+ return qcrypto_builtin_rsa_private_key_parse(key, keylen, errp);
+
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PUBLIC:
+ return qcrypto_builtin_rsa_public_key_parse(key, keylen, errp);
+
+ default:
+ error_setg(errp, "Unknown key type: %d", type);
+ return NULL;
+ }
+}
diff --git a/crypto/rsakey-nettle.c.inc b/crypto/rsakey-nettle.c.inc
new file mode 100644
index 0000000..cc49872
--- /dev/null
+++ b/crypto/rsakey-nettle.c.inc
@@ -0,0 +1,158 @@
+/*
+ * QEMU Crypto akcipher algorithms
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include <nettle/asn1.h>
+
+#include "qemu/osdep.h"
+#include "qapi/error.h"
+#include "rsakey.h"
+
+static bool DumpMPI(struct asn1_der_iterator *i, QCryptoAkCipherMPI *mpi)
+{
+ mpi->data = g_memdup2(i->data, i->length);
+ mpi->len = i->length;
+ return true;
+}
+
+static bool GetMPI(struct asn1_der_iterator *i, QCryptoAkCipherMPI *mpi)
+{
+ if (asn1_der_iterator_next(i) != ASN1_ITERATOR_PRIMITIVE ||
+ i->type != ASN1_INTEGER) {
+ return false;
+ }
+ return DumpMPI(i, mpi);
+}
+
+/**
+ * RsaPrivKey ::= SEQUENCE {
+ * version INTEGER
+ * n INTEGER
+ * e INTEGER
+ * d INTEGER
+ * p INTEGER
+ * q INTEGER
+ * dp INTEGER
+ * dq INTEGER
+ * u INTEGER
+ * otherPrimeInfos OtherPrimeInfos OPTIONAL
+ * }
+ */
+static QCryptoAkCipherRSAKey *qcrypto_nettle_rsa_private_key_parse(
+ const uint8_t *key, size_t keylen, Error **errp)
+{
+ QCryptoAkCipherRSAKey *rsa = g_new0(QCryptoAkCipherRSAKey, 1);
+ struct asn1_der_iterator i;
+ uint32_t version;
+ int tag;
+
+ /* Parse entire struct */
+ if (asn1_der_iterator_first(&i, keylen, key) != ASN1_ITERATOR_CONSTRUCTED ||
+ i.type != ASN1_SEQUENCE ||
+ asn1_der_decode_constructed_last(&i) != ASN1_ITERATOR_PRIMITIVE ||
+ i.type != ASN1_INTEGER ||
+ !asn1_der_get_uint32(&i, &version) ||
+ version > 1 ||
+ !GetMPI(&i, &rsa->n) ||
+ !GetMPI(&i, &rsa->e) ||
+ !GetMPI(&i, &rsa->d) ||
+ !GetMPI(&i, &rsa->p) ||
+ !GetMPI(&i, &rsa->q) ||
+ !GetMPI(&i, &rsa->dp) ||
+ !GetMPI(&i, &rsa->dq) ||
+ !GetMPI(&i, &rsa->u)) {
+ goto error;
+ }
+
+ if (version == 1) {
+ tag = asn1_der_iterator_next(&i);
+ /**
+ * According to the standard otherPrimeInfos must be present for
+ * version 1. There is no strict verification here, this is to be
+ * compatible with the unit test of the kernel. TODO: remove this
+ * until linux-kernel's unit-test is fixed;
+ */
+ if (tag == ASN1_ITERATOR_END) {
+ return rsa;
+ }
+ if (tag != ASN1_ITERATOR_CONSTRUCTED ||
+ i.type != ASN1_SEQUENCE) {
+ goto error;
+ }
+ }
+
+ if (asn1_der_iterator_next(&i) != ASN1_ITERATOR_END) {
+ goto error;
+ }
+
+ return rsa;
+
+error:
+ error_setg(errp, "Failed to parse RSA private key");
+ qcrypto_akcipher_rsakey_free(rsa);
+ return NULL;
+}
+
+/**
+ * RsaPubKey ::= SEQUENCE {
+ * n INTEGER
+ * e INTEGER
+ * }
+ */
+static QCryptoAkCipherRSAKey *qcrypto_nettle_rsa_public_key_parse(
+ const uint8_t *key, size_t keylen, Error **errp)
+{
+
+ QCryptoAkCipherRSAKey *rsa = g_new0(QCryptoAkCipherRSAKey, 1);
+ struct asn1_der_iterator i;
+
+ if (asn1_der_iterator_first(&i, keylen, key) != ASN1_ITERATOR_CONSTRUCTED ||
+ i.type != ASN1_SEQUENCE ||
+ asn1_der_decode_constructed_last(&i) != ASN1_ITERATOR_PRIMITIVE ||
+ !DumpMPI(&i, &rsa->n) ||
+ !GetMPI(&i, &rsa->e) ||
+ asn1_der_iterator_next(&i) != ASN1_ITERATOR_END) {
+ goto error;
+ }
+
+ return rsa;
+
+error:
+ error_setg(errp, "Failed to parse RSA public key");
+ qcrypto_akcipher_rsakey_free(rsa);
+ return NULL;
+}
+
+QCryptoAkCipherRSAKey *qcrypto_akcipher_rsakey_parse(
+ QCryptoAkCipherKeyType type, const uint8_t *key,
+ size_t keylen, Error **errp)
+{
+ switch (type) {
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PRIVATE:
+ return qcrypto_nettle_rsa_private_key_parse(key, keylen, errp);
+
+ case QCRYPTO_AKCIPHER_KEY_TYPE_PUBLIC:
+ return qcrypto_nettle_rsa_public_key_parse(key, keylen, errp);
+
+ default:
+ error_setg(errp, "Unknown key type: %d", type);
+ return NULL;
+ }
+}
diff --git a/crypto/rsakey.c b/crypto/rsakey.c
new file mode 100644
index 0000000..cc40e07
--- /dev/null
+++ b/crypto/rsakey.c
@@ -0,0 +1,44 @@
+/*
+ * QEMU Crypto RSA key parser
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#include "rsakey.h"
+
+void qcrypto_akcipher_rsakey_free(QCryptoAkCipherRSAKey *rsa_key)
+{
+ if (!rsa_key) {
+ return;
+ }
+ g_free(rsa_key->n.data);
+ g_free(rsa_key->e.data);
+ g_free(rsa_key->d.data);
+ g_free(rsa_key->p.data);
+ g_free(rsa_key->q.data);
+ g_free(rsa_key->dp.data);
+ g_free(rsa_key->dq.data);
+ g_free(rsa_key->u.data);
+ g_free(rsa_key);
+}
+
+#if defined(CONFIG_NETTLE) && defined(CONFIG_HOGWEED)
+#include "rsakey-nettle.c.inc"
+#else
+#include "rsakey-builtin.c.inc"
+#endif
diff --git a/crypto/rsakey.h b/crypto/rsakey.h
new file mode 100644
index 0000000..974b76f
--- /dev/null
+++ b/crypto/rsakey.h
@@ -0,0 +1,92 @@
+/*
+ * QEMU Crypto RSA key parser
+ *
+ * Copyright (c) 2022 Bytedance
+ * Author: lei he <helei.sig11@bytedance.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+#ifndef QCRYPTO_RSAKEY_H
+#define QCRYPTO_RSAKEY_H
+
+#include "qemu/osdep.h"
+#include "qemu/host-utils.h"
+#include "crypto/akcipher.h"
+
+typedef struct QCryptoAkCipherRSAKey QCryptoAkCipherRSAKey;
+typedef struct QCryptoAkCipherMPI QCryptoAkCipherMPI;
+
+/**
+ * Multiple precious integer, encoded as two' complement,
+ * copied directly from DER encoded ASN.1 structures.
+ */
+struct QCryptoAkCipherMPI {
+ uint8_t *data;
+ size_t len;
+};
+
+/* See rfc2437: https://datatracker.ietf.org/doc/html/rfc2437 */
+struct QCryptoAkCipherRSAKey {
+ /* The modulus */
+ QCryptoAkCipherMPI n;
+ /* The public exponent */
+ QCryptoAkCipherMPI e;
+ /* The private exponent */
+ QCryptoAkCipherMPI d;
+ /* The first factor */
+ QCryptoAkCipherMPI p;
+ /* The second factor */
+ QCryptoAkCipherMPI q;
+ /* The first factor's exponent */
+ QCryptoAkCipherMPI dp;
+ /* The second factor's exponent */
+ QCryptoAkCipherMPI dq;
+ /* The CRT coefficient */
+ QCryptoAkCipherMPI u;
+};
+
+/**
+ * Parse DER encoded ASN.1 RSA keys, expected ASN.1 schemas:
+ * RsaPrivKey ::= SEQUENCE {
+ * version INTEGER
+ * n INTEGER
+ * e INTEGER
+ * d INTEGER
+ * p INTEGER
+ * q INTEGER
+ * dp INTEGER
+ * dq INTEGER
+ * u INTEGER
+ * otherPrimeInfos OtherPrimeInfos OPTIONAL
+ * }
+ *
+ * RsaPubKey ::= SEQUENCE {
+ * n INTEGER
+ * e INTEGER
+ * }
+ *
+ * Returns: On success QCryptoAkCipherRSAKey is returned, otherwise returns NULL
+ */
+QCryptoAkCipherRSAKey *qcrypto_akcipher_rsakey_parse(
+ QCryptoAkCipherKeyType type,
+ const uint8_t *key, size_t keylen, Error **errp);
+
+void qcrypto_akcipher_rsakey_free(QCryptoAkCipherRSAKey *key);
+
+G_DEFINE_AUTOPTR_CLEANUP_FUNC(QCryptoAkCipherRSAKey,
+ qcrypto_akcipher_rsakey_free);
+
+#endif