stream_salsa208_ref.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. version 20140420
  3. D. J. Bernstein
  4. Public domain.
  5. */
  6. #include <stdint.h>
  7. #include "crypto_core_salsa208.h"
  8. #include "crypto_stream_salsa208.h"
  9. #include "utils.h"
  10. int
  11. crypto_stream_salsa208(unsigned char *c, unsigned long long clen,
  12. const unsigned char *n, const unsigned char *k)
  13. {
  14. unsigned char in[16];
  15. unsigned char block[64];
  16. unsigned char kcopy[32];
  17. unsigned int i;
  18. unsigned int u;
  19. if (!clen) {
  20. return 0;
  21. }
  22. for (i = 0; i < 32; ++i) {
  23. kcopy[i] = k[i];
  24. }
  25. for (i = 0; i < 8; ++i) {
  26. in[i] = n[i];
  27. }
  28. for (i = 8; i < 16; ++i) {
  29. in[i] = 0;
  30. }
  31. while (clen >= 64) {
  32. crypto_core_salsa208(c, in, kcopy, NULL);
  33. u = 1;
  34. for (i = 8; i < 16; ++i) {
  35. u += (unsigned int)in[i];
  36. in[i] = u;
  37. u >>= 8;
  38. }
  39. clen -= 64;
  40. c += 64;
  41. }
  42. if (clen) {
  43. crypto_core_salsa208(block, in, kcopy, NULL);
  44. for (i = 0; i < (unsigned int)clen; ++i) {
  45. c[i] = block[i];
  46. }
  47. }
  48. sodium_memzero(block, sizeof block);
  49. sodium_memzero(kcopy, sizeof kcopy);
  50. return 0;
  51. }
  52. int
  53. crypto_stream_salsa208_xor(unsigned char *c, const unsigned char *m,
  54. unsigned long long mlen, const unsigned char *n,
  55. const unsigned char *k)
  56. {
  57. unsigned char in[16];
  58. unsigned char block[64];
  59. unsigned char kcopy[32];
  60. unsigned int i;
  61. unsigned int u;
  62. if (!mlen) {
  63. return 0;
  64. }
  65. for (i = 0; i < 32; ++i) {
  66. kcopy[i] = k[i];
  67. }
  68. for (i = 0; i < 8; ++i) {
  69. in[i] = n[i];
  70. }
  71. for (i = 8; i < 16; ++i) {
  72. in[i] = 0;
  73. }
  74. while (mlen >= 64) {
  75. crypto_core_salsa208(block, in, kcopy, NULL);
  76. for (i = 0; i < 64; ++i) {
  77. c[i] = m[i] ^ block[i];
  78. }
  79. u = 1;
  80. for (i = 8; i < 16; ++i) {
  81. u += (unsigned int)in[i];
  82. in[i] = u;
  83. u >>= 8;
  84. }
  85. mlen -= 64;
  86. c += 64;
  87. m += 64;
  88. }
  89. if (mlen) {
  90. crypto_core_salsa208(block, in, kcopy, NULL);
  91. for (i = 0; i < (unsigned int)mlen; ++i) {
  92. c[i] = m[i] ^ block[i];
  93. }
  94. }
  95. sodium_memzero(block, sizeof block);
  96. sodium_memzero(kcopy, sizeof kcopy);
  97. return 0;
  98. }