chacha_drbg.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * This file is part of the Trezor project, https://trezor.io/
  3. *
  4. * Copyright (c) SatoshiLabs
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #ifndef __CHACHA_DRBG__
  20. #define __CHACHA_DRBG__
  21. #include "chacha20poly1305/chacha20poly1305.h"
  22. #include "sha2.h"
  23. // A very fast deterministic random bit generator based on CTR_DRBG in NIST SP
  24. // 800-90A. Chacha is used instead of a block cipher in the counter mode, SHA256
  25. // is used as a derivation function. The highest supported security strength is
  26. // at least 256 bits. Reseeding is left up to caller.
  27. // Length of inputs of chacha_drbg_init (entropy and nonce) or
  28. // chacha_drbg_reseed (entropy and additional_input) that fill exactly
  29. // block_count blocks of hash function in derivation_function. There is no need
  30. // the input to have this length, it's just an optimalization.
  31. #define CHACHA_DRBG_OPTIMAL_RESEED_LENGTH(block_count) \
  32. ((block_count)*SHA256_BLOCK_LENGTH - 1 - 4 - 9)
  33. // 1 = sizeof(counter), 4 = sizeof(output_length) in
  34. // derivation_function, 9 is length of SHA256 padding of message
  35. // aligned to bytes
  36. typedef struct _CHACHA_DRBG_CTX {
  37. ECRYPT_ctx chacha_ctx;
  38. uint32_t reseed_counter;
  39. } CHACHA_DRBG_CTX;
  40. void chacha_drbg_init(CHACHA_DRBG_CTX *ctx, const uint8_t *entropy,
  41. size_t entropy_length, const uint8_t *nonce,
  42. size_t nonce_length);
  43. void chacha_drbg_generate(CHACHA_DRBG_CTX *ctx, uint8_t *output,
  44. size_t output_length);
  45. void chacha_drbg_reseed(CHACHA_DRBG_CTX *ctx, const uint8_t *entropy,
  46. size_t entropy_length, const uint8_t *additional_input,
  47. size_t additional_input_length);
  48. #endif // __CHACHA_DRBG__