You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.2 KiB

  1. /*
  2. prg.c version 20151120
  3. Andreas Hülsing
  4. Public domain.
  5. */
  6. #include "chacha.h"
  7. #include "prg.h"
  8. #include <stdio.h>
  9. #include <openssl/sha.h>
  10. #include <openssl/hmac.h>
  11. #include <openssl/evp.h>
  12. const unsigned char zero_nonce[12] = {0};
  13. /**
  14. * Generates rlen output bytes using ChaCha20 with a zero nonce and counter = 0
  15. */
  16. void prg(unsigned char *r, unsigned long long rlen, const unsigned char *key, unsigned int key_len)
  17. {
  18. if (key_len == 32) {
  19. CRYPTO_chacha_20_keystream(r, rlen, key, zero_nonce, 0);
  20. }
  21. else {
  22. if (key_len == 64) {
  23. unsigned long long left = rlen;
  24. u_int32_t counter = 0;
  25. unsigned char *c = (unsigned char*)&counter;
  26. unsigned int length;
  27. unsigned int i = 0;
  28. unsigned char tmp[64];
  29. while (left > 0) {
  30. HMAC(EVP_sha512(), key, key_len, c , 4, tmp, &length);
  31. if (length != 64) {
  32. fprintf(stderr, "HMAC outputs %d bytes... That should not happen...", length);
  33. }
  34. for (i = 0; ((i < length) && (i < left)); i++) {
  35. r[rlen-left+i] = tmp[i];
  36. }
  37. left -= length;
  38. counter++;
  39. }
  40. }
  41. else {
  42. fprintf(stderr,"prg.c:: Code only supports 32 byte and 64 byte seeds");
  43. }
  44. }
  45. }
  46. /**
  47. * Generates n output bytes using ChaCha20 (n=32) or HMAC-SHA2-512 (n=64).
  48. *
  49. * For ChaCha, nonce and counter are set depending on the address addr. For HMAC, addr is used as message.
  50. */
  51. void prg_with_counter(unsigned char *r, const unsigned char *key, unsigned int n, const unsigned char addr[16])
  52. {
  53. int i;
  54. unsigned char nonce[12];
  55. if (n == 32) {
  56. for (i = 0; i < 12; i++) {
  57. nonce[i] = addr[i];
  58. }
  59. uint32_t counter;
  60. counter = (((uint32_t)addr[12]) << 24) | (((uint32_t)addr[13]) << 16) | (((uint32_t)addr[14]) << 8) | addr[15];
  61. // TODO: Check address handling. Endianess?
  62. CRYPTO_chacha_20_keystream(r, n, key, nonce, counter);
  63. }
  64. else {
  65. if (n == 64) {
  66. unsigned int length;
  67. HMAC(EVP_sha512(), key, n, addr, 16, r, &length);
  68. if (length != 64) {
  69. fprintf(stderr, "HMAC outputs %d bytes... That should not happen...", length);
  70. }
  71. }
  72. else {
  73. fprintf(stderr,"prg.c:: Code only supports 32 byte and 64 byte seeds");
  74. }
  75. }
  76. }