aboutsummaryrefslogtreecommitdiffhomepage
path: root/pyecsca/ec/scalar.py
diff options
context:
space:
mode:
authorJ08nY2023-08-24 17:28:41 +0200
committerJ08nY2023-08-24 17:28:41 +0200
commit2bd18931be9a00bcee3e6e1e50de8188b7f15a07 (patch)
tree9a07344ac37e7e797be0c831cd8fd3c0ea1b951d /pyecsca/ec/scalar.py
parentb5801a2acfdd149cdb5b24985992e43afdfb9311 (diff)
downloadpyecsca-2bd18931be9a00bcee3e6e1e50de8188b7f15a07.tar.gz
pyecsca-2bd18931be9a00bcee3e6e1e50de8188b7f15a07.tar.zst
pyecsca-2bd18931be9a00bcee3e6e1e50de8188b7f15a07.zip
Add FixedWindowLTRMultiplier.
Diffstat (limited to 'pyecsca/ec/scalar.py')
-rw-r--r--pyecsca/ec/scalar.py63
1 files changed, 63 insertions, 0 deletions
diff --git a/pyecsca/ec/scalar.py b/pyecsca/ec/scalar.py
new file mode 100644
index 0000000..06058a0
--- /dev/null
+++ b/pyecsca/ec/scalar.py
@@ -0,0 +1,63 @@
+"""Provides functions for computing various scalar representations (like NAF, or different bases)."""
+from typing import List
+
+from public import public
+
+
+@public
+def convert(i: int, base: int) -> List[int]:
+ """
+ Convert an integer to base.
+
+ :param i:
+ :param base:
+ :return:
+ """
+ if i == 0:
+ return [0]
+ res = []
+ while i:
+ i, r = divmod(i, base)
+ res.append(r)
+ return res
+
+
+@public
+def wnaf(k: int, w: int) -> List[int]:
+ """
+ Compute width `w` NAF (Non-Adjacent Form) of the scalar `k`.
+
+ :param k: The scalar.
+ :param w: The width.
+ :return: The NAF.
+ """
+ half_width = 2 ** (w - 1)
+ full_width = half_width * 2
+
+ def mods(val: int) -> int:
+ val_mod = val % full_width
+ if val_mod > half_width:
+ val_mod -= full_width
+ return val_mod
+
+ result: List[int] = []
+ while k >= 1:
+ if k & 1:
+ k_val = mods(k)
+ result.insert(0, k_val)
+ k -= k_val
+ else:
+ result.insert(0, 0)
+ k >>= 1
+ return result
+
+
+@public
+def naf(k: int) -> List[int]:
+ """
+ Compute the NAF (Non-Adjacent Form) of the scalar `k`.
+
+ :param k: The scalar.
+ :return: The NAF.
+ """
+ return wnaf(k, 2)