ec.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 json_t *
  31. jwk_make_execute(jose_cfg_t *cfg, const json_t *jwk)
  32. {
  33. openssl_auto(EC_KEY) *key = NULL;
  34. const char *crv = "P-256";
  35. int nid = NID_undef;
  36. if (!jwk_make_handles(cfg, jwk))
  37. return false;
  38. if (json_unpack((json_t *) jwk, "{s?s}", "crv", &crv) == -1)
  39. return false;
  40. switch (str2enum(crv, "P-256", "P-384", "P-521", NULL)) {
  41. case 0: nid = NID_X9_62_prime256v1; break;
  42. case 1: nid = NID_secp384r1; break;
  43. case 2: nid = NID_secp521r1; break;
  44. default: return false;
  45. }
  46. key = EC_KEY_new_by_curve_name(nid);
  47. if (!key)
  48. return false;
  49. if (EC_KEY_generate_key(key) <= 0)
  50. return false;
  51. return json_pack("{s:o}", "upd", jose_openssl_jwk_from_EC_KEY(cfg, key));
  52. }
  53. static void __attribute__((constructor))
  54. constructor(void)
  55. {
  56. static jose_hook_jwk_t jwk = {
  57. .kind = JOSE_HOOK_JWK_KIND_MAKE,
  58. .make.handles = jwk_make_handles,
  59. .make.execute = jwk_make_execute
  60. };
  61. jose_hook_jwk_push(&jwk);
  62. }