sha2.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (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 <openssl/sha.h>
  10. #include <openssl/crypto.h>
  11. #include <openssl/core_numbers.h>
  12. #include "internal/provider_algs.h"
  13. /*
  14. * Forward declaration of everything implemented here. This is not strictly
  15. * necessary for the compiler, but provides an assurance that the signatures
  16. * of the functions in the dispatch table are correct.
  17. */
  18. static OSSL_OP_digest_newctx_fn sha256_newctx;
  19. #if 0 /* Not defined here */
  20. static OSSL_OP_digest_init_fn sha256_init;
  21. static OSSL_OP_digest_update_fn sha256_update;
  22. #endif
  23. static OSSL_OP_digest_final_fn sha256_final;
  24. static OSSL_OP_digest_freectx_fn sha256_freectx;
  25. static OSSL_OP_digest_dupctx_fn sha256_dupctx;
  26. static OSSL_OP_digest_size_fn sha256_size;
  27. static OSSL_OP_digest_block_size_fn sha256_size;
  28. static int sha256_final(void *ctx,
  29. unsigned char *md, size_t *mdl, size_t mdsz)
  30. {
  31. if (mdsz >= SHA256_DIGEST_LENGTH
  32. && SHA256_Final(md, ctx)) {
  33. *mdl = SHA256_DIGEST_LENGTH;
  34. return 1;
  35. }
  36. return 0;
  37. }
  38. static void *sha256_newctx(void)
  39. {
  40. SHA256_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
  41. return ctx;
  42. }
  43. static void sha256_freectx(void *vctx)
  44. {
  45. SHA256_CTX *ctx = (SHA256_CTX *)vctx;
  46. OPENSSL_clear_free(ctx, sizeof(*ctx));
  47. }
  48. static void *sha256_dupctx(void *ctx)
  49. {
  50. SHA256_CTX *in = (SHA256_CTX *)ctx;
  51. SHA256_CTX *ret = OPENSSL_malloc(sizeof(*ret));
  52. *ret = *in;
  53. return ret;
  54. }
  55. static size_t sha256_size(void)
  56. {
  57. return SHA256_DIGEST_LENGTH;
  58. }
  59. static size_t sha256_block_size(void)
  60. {
  61. return SHA256_CBLOCK;
  62. }
  63. const OSSL_DISPATCH sha256_functions[] = {
  64. { OSSL_FUNC_DIGEST_NEWCTX, (void (*)(void))sha256_newctx },
  65. { OSSL_FUNC_DIGEST_INIT, (void (*)(void))SHA256_Init },
  66. { OSSL_FUNC_DIGEST_UPDATE, (void (*)(void))SHA256_Update },
  67. { OSSL_FUNC_DIGEST_FINAL, (void (*)(void))sha256_final },
  68. { OSSL_FUNC_DIGEST_FREECTX, (void (*)(void))sha256_freectx },
  69. { OSSL_FUNC_DIGEST_DUPCTX, (void (*)(void))sha256_dupctx },
  70. { OSSL_FUNC_DIGEST_SIZE, (void (*)(void))sha256_size },
  71. { OSSL_FUNC_DIGEST_BLOCK_SIZE, (void (*)(void))sha256_block_size },
  72. { 0, NULL }
  73. };