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.
 
 
 
 
 

108 lines
2.4 KiB

  1. /**
  2. * @file field.h
  3. * @brief Generic gf header.
  4. * @copyright
  5. * Copyright (c) 2014 Cryptography Research, Inc. \n
  6. * Released under the MIT License. See LICENSE.txt for license information.
  7. * @author Mike Hamburg
  8. */
  9. #ifndef __GF_H__
  10. #define __GF_H__
  11. #include "constant_time.h"
  12. #include "f_field.h"
  13. #include <string.h>
  14. /** Square x, n times. */
  15. static INLINE UNUSED void gf_sqrn (
  16. gf_s *__restrict__ y,
  17. const gf x,
  18. int n
  19. ) {
  20. gf tmp;
  21. assert(n>0);
  22. if (n&1) {
  23. gf_sqr(y,x);
  24. n--;
  25. } else {
  26. gf_sqr(tmp,x);
  27. gf_sqr(y,tmp);
  28. n-=2;
  29. }
  30. for (; n; n-=2) {
  31. gf_sqr(tmp,y);
  32. gf_sqr(y,tmp);
  33. }
  34. }
  35. #define gf_add_nr gf_add_RAW
  36. /** Subtract mod p. Bias by 2 and don't reduce */
  37. static inline void gf_sub_nr ( gf c, const gf a, const gf b ) {
  38. gf_sub_RAW(c,a,b);
  39. gf_bias(c, 2);
  40. if (GF_HEADROOM < 3) gf_weak_reduce(c);
  41. }
  42. /** Subtract mod p. Bias by amt but don't reduce. */
  43. static inline void gf_subx_nr ( gf c, const gf a, const gf b, int amt ) {
  44. gf_sub_RAW(c,a,b);
  45. gf_bias(c, amt);
  46. if (GF_HEADROOM < amt+1) gf_weak_reduce(c);
  47. }
  48. /** Mul by signed int. Not constant-time WRT the sign of that int. */
  49. static inline void gf_mulw(gf c, const gf a, int32_t w) {
  50. if (w>0) {
  51. gf_mulw_unsigned(c, a, w);
  52. } else {
  53. gf_mulw_unsigned(c, a, -w);
  54. gf_sub(c,ZERO,c);
  55. }
  56. }
  57. /** Constant time, x = is_z ? z : y */
  58. static inline void gf_cond_sel(gf x, const gf y, const gf z, mask_t is_z) {
  59. constant_time_select(x,y,z,sizeof(gf),is_z,0);
  60. }
  61. /** Constant time, if (neg) x=-x; */
  62. static inline void gf_cond_neg(gf x, mask_t neg) {
  63. gf y;
  64. gf_sub(y,ZERO,x);
  65. gf_cond_sel(x,x,y,neg);
  66. }
  67. /** Constant time, if (swap) (x,y) = (y,x); */
  68. static inline void
  69. gf_cond_swap(gf x, gf_s *__restrict__ y, mask_t swap) {
  70. constant_time_cond_swap(x,y,sizeof(gf_s),swap);
  71. }
  72. static INLINE void gf_mul_qnr(gf_s *__restrict__ out, const gf x) {
  73. #if P_MOD_8 == 5
  74. /* r = QNR * r0^2 */
  75. gf_mul(out,x,SQRT_MINUS_ONE);
  76. #elif P_MOD_8 == 3 || P_MOD_8 == 7
  77. gf_sub(out,ZERO,x);
  78. #else
  79. #error "Only supporting p=3,5,7 mod 8"
  80. #endif
  81. }
  82. static INLINE void gf_div_qnr(gf_s *__restrict__ out, const gf x) {
  83. #if P_MOD_8 == 5
  84. /* r = QNR * r0^2 */
  85. gf_mul(out,x,SQRT_MINUS_ONE);
  86. gf_sub(out,ZERO,out);
  87. #elif P_MOD_8 == 3 || P_MOD_8 == 7
  88. gf_sub(out,ZERO,x);
  89. #else
  90. #error "Only supporting p=3,5,7 mod 8"
  91. #endif
  92. }
  93. #endif // __GF_H__