mldsa: optimize to read a block once

This commit is contained in:
Sun Yimin 2025-05-28 16:13:40 +08:00 committed by GitHub
parent 3c24ac0690
commit 67ac5da71e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -17,26 +17,26 @@ func rejNTTPoly(rho []byte, s, r byte) nttElement {
G.Write(rho) G.Write(rho)
G.Write([]byte{s, r}) G.Write([]byte{s, r})
//TODO: optimize to read a block once const blockSize = 168 // SHAKE128 block size in bytes
var buf [3]byte var buf [blockSize]byte
var a nttElement var a nttElement
var j int var j int
for { for {
G.Read(buf[:]) G.Read(buf[:])
for i := 0; i < blockSize; i += 3 {
// Algorithm 14, CoeffFromThreeBytes() // Algorithm 14, CoeffFromThreeBytes()
d := uint32(buf[0]) | uint32(buf[1])<<8 | ((uint32(buf[2]) & 0x7f) << 16) d := uint32(buf[i]) | uint32(buf[i+1])<<8 | ((uint32(buf[i+2]) & 0x7f) << 16)
if d < q { if d < q {
a[j] = fieldElement(d) a[j] = fieldElement(d)
j++ j++
} }
if j >= len(a) { if j >= len(a) {
break
}
}
return a return a
}
}
}
} }
// This is a constant time version of n % 5 // This is a constant time version of n % 5
@ -57,15 +57,17 @@ func rejBoundedPoly(rho []byte, eta int, highByte, lowByte byte) ringElement {
H.Write(rho) H.Write(rho)
H.Write([]byte{lowByte, highByte}) H.Write([]byte{lowByte, highByte})
//TODO: optimize to read a block once const blockSize = 136 // SHAKE256 block size in bytes
var buf [1]byte var buf [blockSize]byte
var a ringElement var a ringElement
var j int var offset, j int
H.Read(buf[:])
for { for {
H.Read(buf[:]) z0 := buf[offset] & 0xf
z0 := buf[0] & 0xf z1 := buf[offset] >> 4
z1 := buf[0] >> 4 offset++
if eta == 2 { if eta == 2 {
if subtle.ConstantTimeByteEq(z0, 15) == 0 { if subtle.ConstantTimeByteEq(z0, 15) == 0 {
@ -98,6 +100,10 @@ func rejBoundedPoly(rho []byte, eta int, highByte, lowByte byte) ringElement {
} }
} }
} }
if offset >= blockSize {
H.Read(buf[:])
offset = 0
}
} }
return a return a
} }