chacha_drbg.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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(
  41. CHACHA_DRBG_CTX* ctx,
  42. const uint8_t* entropy,
  43. size_t entropy_length,
  44. const uint8_t* nonce,
  45. size_t nonce_length);
  46. void chacha_drbg_generate(CHACHA_DRBG_CTX* ctx, uint8_t* output, size_t output_length);
  47. void chacha_drbg_reseed(
  48. CHACHA_DRBG_CTX* ctx,
  49. const uint8_t* entropy,
  50. size_t entropy_length,
  51. const uint8_t* additional_input,
  52. size_t additional_input_length);
  53. #endif // __CHACHA_DRBG__