summaryrefslogtreecommitdiff
path: root/src/lib/libssl/src/crypto/bn/bn_lib.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/libssl/src/crypto/bn/bn_lib.c')
-rw-r--r--src/lib/libssl/src/crypto/bn/bn_lib.c52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/lib/libssl/src/crypto/bn/bn_lib.c b/src/lib/libssl/src/crypto/bn/bn_lib.c
index 7a5676de69..5461e6ee7d 100644
--- a/src/lib/libssl/src/crypto/bn/bn_lib.c
+++ b/src/lib/libssl/src/crypto/bn/bn_lib.c
@@ -824,3 +824,55 @@ int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b,
824 } 824 }
825 return bn_cmp_words(a,b,cl); 825 return bn_cmp_words(a,b,cl);
826 } 826 }
827
828/*
829 * Constant-time conditional swap of a and b.
830 * a and b are swapped if condition is not 0. The code assumes that at most one bit of condition is set.
831 * nwords is the number of words to swap. The code assumes that at least nwords are allocated in both a and b,
832 * and that no more than nwords are used by either a or b.
833 * a and b cannot be the same number
834 */
835void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords)
836 {
837 BN_ULONG t;
838 int i;
839
840 bn_wcheck_size(a, nwords);
841 bn_wcheck_size(b, nwords);
842
843 assert(a != b);
844 assert((condition & (condition - 1)) == 0);
845 assert(sizeof(BN_ULONG) >= sizeof(int));
846
847 condition = ((condition - 1) >> (BN_BITS2 - 1)) - 1;
848
849 t = (a->top^b->top) & condition;
850 a->top ^= t;
851 b->top ^= t;
852
853#define BN_CONSTTIME_SWAP(ind) \
854 do { \
855 t = (a->d[ind] ^ b->d[ind]) & condition; \
856 a->d[ind] ^= t; \
857 b->d[ind] ^= t; \
858 } while (0)
859
860
861 switch (nwords) {
862 default:
863 for (i = 10; i < nwords; i++)
864 BN_CONSTTIME_SWAP(i);
865 /* Fallthrough */
866 case 10: BN_CONSTTIME_SWAP(9); /* Fallthrough */
867 case 9: BN_CONSTTIME_SWAP(8); /* Fallthrough */
868 case 8: BN_CONSTTIME_SWAP(7); /* Fallthrough */
869 case 7: BN_CONSTTIME_SWAP(6); /* Fallthrough */
870 case 6: BN_CONSTTIME_SWAP(5); /* Fallthrough */
871 case 5: BN_CONSTTIME_SWAP(4); /* Fallthrough */
872 case 4: BN_CONSTTIME_SWAP(3); /* Fallthrough */
873 case 3: BN_CONSTTIME_SWAP(2); /* Fallthrough */
874 case 2: BN_CONSTTIME_SWAP(1); /* Fallthrough */
875 case 1: BN_CONSTTIME_SWAP(0);
876 }
877#undef BN_CONSTTIME_SWAP
878}