aboutsummaryrefslogtreecommitdiff
path: root/pyecsca/ec/key_generation.py
blob: 6476cac2c1106bb0c87c313b150f0fe3f697372d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from typing import Tuple

from public import public

from .context import ResultAction
from .mod import Mod
from .mult import ScalarMultiplier
from .params import DomainParameters
from .point import Point


@public
class KeygenAction(ResultAction):
    """A key generation."""
    params: DomainParameters

    def __init__(self, params: DomainParameters):
        super().__init__()
        self.params = params

    def __repr__(self):
        return f"{self.__class__.__name__}({self.params})"


@public
class KeyGeneration(object):
    """Key generator."""
    mult: ScalarMultiplier
    params: DomainParameters
    affine: bool

    def __init__(self, mult: ScalarMultiplier, params: DomainParameters, affine: bool = False):
        self.mult = mult
        self.params = params
        self.mult.init(self.params, self.params.generator)
        self.affine = affine

    def generate(self) -> Tuple[Mod, Point]:
        with KeygenAction(self.params) as action:
            privkey = Mod.random(self.params.order)
            pubkey = self.mult.multiply(privkey.x)
            if self.affine:
                pubkey = pubkey.to_affine()
            return action.exit((privkey, pubkey))