1
0

hsh.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. #define _GNU_SOURCE
  18. #include "misc.h"
  19. #include "hsh.h"
  20. #include <jose/b64.h>
  21. #include "hooks.h"
  22. json_t *
  23. hsh(jose_cfg_t *cfg, const char *alg, const void *data, size_t dlen)
  24. {
  25. jose_io_auto_t *_hsh = NULL;
  26. jose_io_auto_t *enc = NULL;
  27. jose_io_auto_t *buf = NULL;
  28. char b[1024] = {};
  29. size_t l = sizeof(b);
  30. buf = jose_io_buffer(cfg, b, &l);
  31. enc = jose_b64_enc_io(buf);
  32. _hsh = hsh_io(cfg, alg, enc);
  33. if (!buf || !enc || !_hsh || !_hsh->feed(_hsh, data, dlen) || !_hsh->done(_hsh))
  34. return NULL;
  35. return json_stringn(b, l);
  36. }
  37. jose_io_t *
  38. hsh_io(jose_cfg_t *cfg, const char *alg, jose_io_t *next)
  39. {
  40. const jose_hook_alg_t *a = NULL;
  41. a = jose_hook_alg_find(JOSE_HOOK_ALG_KIND_HASH, alg);
  42. if (!a)
  43. return NULL;
  44. return a->hash.hsh(a, cfg, next);
  45. }
  46. size_t
  47. hsh_buf(jose_cfg_t *cfg, const char *alg,
  48. const void *data, size_t dlen, void *hash, size_t hlen)
  49. {
  50. const jose_hook_alg_t *a = NULL;
  51. jose_io_auto_t *_hsh = NULL;
  52. jose_io_auto_t *buf = NULL;
  53. a = jose_hook_alg_find(JOSE_HOOK_ALG_KIND_HASH, alg);
  54. if (!a)
  55. return SIZE_MAX;
  56. if (!hash || hlen == 0)
  57. return a->hash.size;
  58. if (hlen < a->hash.size)
  59. return SIZE_MAX;
  60. buf = jose_io_buffer(cfg, hash, &hlen);
  61. _hsh = a->hash.hsh(a, cfg, buf);
  62. if (!buf || !_hsh || !_hsh->feed(_hsh, data, dlen) || !_hsh->done(_hsh))
  63. return SIZE_MAX;
  64. return hlen;
  65. }