hm_ameth.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright 2007-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/evp.h>
  12. #include "internal/asn1_int.h"
  13. #include "internal/evp_int.h"
  14. /*
  15. * HMAC "ASN1" method. This is just here to indicate the maximum HMAC output
  16. * length and to free up an HMAC key.
  17. */
  18. static int hmac_size(const EVP_PKEY *pkey)
  19. {
  20. return EVP_MAX_MD_SIZE;
  21. }
  22. static void hmac_key_free(EVP_PKEY *pkey)
  23. {
  24. ASN1_OCTET_STRING *os = EVP_PKEY_get0(pkey);
  25. if (os) {
  26. if (os->data)
  27. OPENSSL_cleanse(os->data, os->length);
  28. ASN1_OCTET_STRING_free(os);
  29. }
  30. }
  31. static int hmac_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
  32. {
  33. switch (op) {
  34. case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
  35. *(int *)arg2 = NID_sha256;
  36. return 1;
  37. default:
  38. return -2;
  39. }
  40. }
  41. static int hmac_pkey_public_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
  42. {
  43. return ASN1_OCTET_STRING_cmp(EVP_PKEY_get0(a), EVP_PKEY_get0(b));
  44. }
  45. static int hmac_set_priv_key(EVP_PKEY *pkey, const unsigned char *priv,
  46. size_t len)
  47. {
  48. ASN1_OCTET_STRING *os;
  49. if (pkey->pkey.ptr != NULL)
  50. return 0;
  51. os = ASN1_OCTET_STRING_new();
  52. if (os == NULL)
  53. return 0;
  54. if (!ASN1_OCTET_STRING_set(os, priv, len)) {
  55. ASN1_OCTET_STRING_free(os);
  56. return 0;
  57. }
  58. pkey->pkey.ptr = os;
  59. return 1;
  60. }
  61. const EVP_PKEY_ASN1_METHOD hmac_asn1_meth = {
  62. EVP_PKEY_HMAC,
  63. EVP_PKEY_HMAC,
  64. 0,
  65. "HMAC",
  66. "OpenSSL HMAC method",
  67. 0, 0, hmac_pkey_public_cmp, 0,
  68. 0, 0, 0,
  69. hmac_size,
  70. 0, 0,
  71. 0, 0, 0, 0, 0, 0, 0,
  72. hmac_key_free,
  73. hmac_pkey_ctrl,
  74. NULL,
  75. NULL,
  76. NULL,
  77. NULL,
  78. NULL,
  79. NULL,
  80. NULL,
  81. NULL,
  82. hmac_set_priv_key,
  83. NULL,
  84. };