rsakey.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * QEMU Crypto RSA key parser
  3. *
  4. * Copyright (c) 2022 Bytedance
  5. * Author: lei he <helei.sig11@bytedance.com>
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library 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 GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. #include "qemu/osdep.h"
  22. #include "der.h"
  23. #include "rsakey.h"
  24. void qcrypto_akcipher_rsakey_free(QCryptoAkCipherRSAKey *rsa_key)
  25. {
  26. if (!rsa_key) {
  27. return;
  28. }
  29. g_free(rsa_key->n.data);
  30. g_free(rsa_key->e.data);
  31. g_free(rsa_key->d.data);
  32. g_free(rsa_key->p.data);
  33. g_free(rsa_key->q.data);
  34. g_free(rsa_key->dp.data);
  35. g_free(rsa_key->dq.data);
  36. g_free(rsa_key->u.data);
  37. g_free(rsa_key);
  38. }
  39. /**
  40. * PKCS#8 private key info for RSA
  41. *
  42. * PrivateKeyInfo ::= SEQUENCE {
  43. * version INTEGER,
  44. * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  45. * privateKey OCTET STRING,
  46. * attributes [0] IMPLICIT Attributes OPTIONAL
  47. * }
  48. */
  49. void qcrypto_akcipher_rsakey_export_p8info(const uint8_t *key,
  50. size_t keylen,
  51. uint8_t **dst,
  52. size_t *dlen)
  53. {
  54. QCryptoEncodeContext *ctx = qcrypto_der_encode_ctx_new();
  55. uint8_t version = 0;
  56. qcrypto_der_encode_seq_begin(ctx);
  57. /* version */
  58. qcrypto_der_encode_int(ctx, &version, sizeof(version));
  59. /* algorithm identifier */
  60. qcrypto_der_encode_seq_begin(ctx);
  61. qcrypto_der_encode_oid(ctx, (uint8_t *)QCRYPTO_OID_rsaEncryption,
  62. sizeof(QCRYPTO_OID_rsaEncryption) - 1);
  63. qcrypto_der_encode_null(ctx);
  64. qcrypto_der_encode_seq_end(ctx);
  65. /* RSA private key */
  66. qcrypto_der_encode_octet_str(ctx, key, keylen);
  67. qcrypto_der_encode_seq_end(ctx);
  68. *dlen = qcrypto_der_encode_ctx_buffer_len(ctx);
  69. *dst = g_malloc(*dlen);
  70. qcrypto_der_encode_ctx_flush_and_free(ctx, *dst);
  71. }
  72. #if defined(CONFIG_NETTLE) && defined(CONFIG_HOGWEED)
  73. #include "rsakey-nettle.c.inc"
  74. #else
  75. #include "rsakey-builtin.c.inc"
  76. #endif