salsa20_ref.c 2.6 KB

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