Move clamped Fq decoding into fq.lua

This commit is contained in:
Miguel Oliveira 2022-03-02 15:18:28 -03:00
parent d06c4309cf
commit 59647d1a96
No known key found for this signature in database
GPG key ID: 2C2BE789E1377025
2 changed files with 20 additions and 14 deletions

View file

@ -280,6 +280,23 @@ local function decodeWide(str)
return add(montgomery(low), montgomery(montgomery(high))) return add(montgomery(low), montgomery(montgomery(high)))
end end
--- Decodes a scalar using the X25519/Ed25519 bit clamping scheme.
--
-- @tparam string str A 32-byte string encoding some little-endian number a.
-- @treturn 2²⁶⁵ * clamp(a) mod q as 11 linbs in [0..2²⁴).
--
local function decodeClamped(str)
-- Decode.
local words = {("<I3I3I3I3I3I3I3I3I3I3I2"):unpack(str)} words[12] = nil
-- Clamp.
words[1] = bit32.band(words[1], 0xfffff8)
words[11] = bit32.band(words[11], 0x7fff)
words[11] = bit32.bor(words[11], 0x4000)
return montgomery(words)
end
--- Returns a scalar in binary. --- Returns a scalar in binary.
-- --
-- @tparam {number...} a A number a < q as limbs in [0..2²⁴). -- @tparam {number...} a A number a < q as limbs in [0..2²⁴).
@ -300,5 +317,6 @@ return {
encode = encode, encode = encode,
decode = decode, decode = decode,
decodeWide = decodeWide, decodeWide = decodeWide,
decodeClamped = decodeClamped,
bits = bits, bits = bits,
} }

View file

@ -25,18 +25,6 @@ local function fqRandom()
return fq.decodeWide(random.random(64)) return fq.decodeWide(random.random(64))
end end
local function fqDecodeStd(str)
-- Decode.
local words = {("<I3I3I3I3I3I3I3I3I3I3I2"):unpack(str)} words[12] = nil
-- Clamp.
words[1] = bit32.band(words[1], 0xfffff8)
words[11] = bit32.band(words[11], 0x7fff)
words[11] = bit32.bor(words[11], 0x4000)
return fq.montgomery(words)
end
local function ladder8(dx, bits) local function ladder8(dx, bits)
local x1 = fp.num(1) local x1 = fp.num(1)
local z1 = fp.num(0) local z1 = fp.num(0)
@ -68,7 +56,7 @@ end
local mod = {} local mod = {}
function mod.secretKeyInit(sk) function mod.secretKeyInit(sk)
sk = fqDecodeStd(sk) sk = fq.decodeClamped(sk)
-- Set up the mask. -- Set up the mask.
local sks = {} local sks = {}
@ -119,7 +107,7 @@ function mod.exchange(sks, pk, mc)
assert(#mc == 32, "multiplier length must be 32") assert(#mc == 32, "multiplier length must be 32")
-- Get the multiplier in Fq. -- Get the multiplier in Fq.
mc = fqDecodeStd(mc) mc = fq.decodeClamped(mc)
-- Multiply secret key members and add them together. -- Multiply secret key members and add them together.
-- This unwraps into the "true" secret key times the multiplier (mod q). -- This unwraps into the "true" secret key times the multiplier (mod q).