Use rejection sampling to implement `random` for `Fp` and `Scalar`.

Signed-off-by: Daira Hopwood <daira@jacaranda.org>
This commit is contained in:
Daira Hopwood 2021-05-06 14:50:58 +01:00 committed by therealyingtong
parent 72cae20b61
commit a7a1e5b217
1 changed files with 11 additions and 2 deletions

View File

@ -32,7 +32,11 @@ class Fp(FieldElement):
return Fp(leos2ip(buf), strict=True)
def random(randbytes):
return Fp(leos2ip(randbytes(32)), strict=False)
while True:
try:
return Fp(leos2ip(randbytes(32)), strict=True)
except ValueError:
pass
def __init__(self, s, strict=False):
FieldElement.__init__(self, Fp, s, p, strict=strict)
@ -98,7 +102,12 @@ class Scalar(FieldElement):
return Scalar(leos2ip(buf), strict=True)
def random(randbytes):
return Scalar(leos2ip(randbytes(32)), strict=False)
while True:
try:
return Scalar(leos2ip(randbytes(32)), strict=True)
except ValueError:
pass
Fp.ZERO = Fp(0)
Fp.ONE = Fp(1)