1
0

ec.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
  2. /*
  3. * Copyright 2016 Red Hat, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. #include "misc.h"
  18. #include "../hooks.h"
  19. #include <jose/openssl.h>
  20. #include <string.h>
  21. declare_cleanup(EC_KEY)
  22. static bool
  23. jwk_make_handles(jose_cfg_t *cfg, const json_t *jwk)
  24. {
  25. const char *kty = NULL;
  26. if (json_unpack((json_t *) jwk, "{s:s}", "kty", &kty) == -1)
  27. return false;
  28. return strcmp(kty, "EC") == 0;
  29. }
  30. static bool
  31. jwk_make_execute(jose_cfg_t *cfg, json_t *jwk)
  32. {
  33. openssl_auto(EC_KEY) *key = NULL;
  34. const char *crv = "P-256";
  35. json_auto_t *out = NULL;
  36. int nid = NID_undef;
  37. if (!jwk_make_handles(cfg, jwk))
  38. return false;
  39. if (json_unpack(jwk, "{s?s}", "crv", &crv) < 0)
  40. return false;
  41. switch (str2enum(crv, "P-256", "P-384", "P-521", NULL)) {
  42. case 0: nid = NID_X9_62_prime256v1; break;
  43. case 1: nid = NID_secp384r1; break;
  44. case 2: nid = NID_secp521r1; break;
  45. default: return false;
  46. }
  47. key = EC_KEY_new_by_curve_name(nid);
  48. if (!key)
  49. return false;
  50. if (EC_KEY_generate_key(key) <= 0)
  51. return false;
  52. out = jose_openssl_jwk_from_EC_KEY(cfg, key);
  53. if (!out)
  54. return false;
  55. return copy_val(out, jwk, "crv", "x", "y", "d", NULL);
  56. }
  57. static void __attribute__((constructor))
  58. constructor(void)
  59. {
  60. static jose_hook_jwk_t jwk = {
  61. .kind = JOSE_HOOK_JWK_KIND_MAKE,
  62. .make.handles = jwk_make_handles,
  63. .make.execute = jwk_make_execute
  64. };
  65. jose_hook_jwk_push(&jwk);
  66. }