1
0

ec.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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", "secp256k1", 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. case 3: nid = NID_secp256k1; break;
  46. default: return false;
  47. }
  48. key = EC_KEY_new_by_curve_name(nid);
  49. if (!key)
  50. return false;
  51. if (EC_KEY_generate_key(key) <= 0)
  52. return false;
  53. out = jose_openssl_jwk_from_EC_KEY(cfg, key);
  54. if (!out)
  55. return false;
  56. return copy_val(out, jwk, "crv", "x", "y", "d", NULL);
  57. }
  58. static void __attribute__((constructor))
  59. constructor(void)
  60. {
  61. static jose_hook_jwk_t jwk = {
  62. .kind = JOSE_HOOK_JWK_KIND_MAKE,
  63. .make.handles = jwk_make_handles,
  64. .make.execute = jwk_make_execute
  65. };
  66. jose_hook_jwk_push(&jwk);
  67. }