Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expander uses io.Writer to pass the hash input. #10

Draft
wants to merge 4 commits into
base: h2cTests
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions .etc/golangci.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
---
linters:
disable-all: true
enable:
# - lll
# - gocritic
# - gocognit
# - lll
# - gocritic
# - gocognit
# - interfacer (deprecated since v1.38.0)
# - scopelint (deprecated since v1.39.0)
# - golint (deprecated since v1.41.0)
- bodyclose
- deadcode
- depguard
Expand All @@ -14,15 +18,12 @@ linters:
- gocyclo
- gofmt
- goimports
- golint
- gosec
- gosimple
- govet
- ineffassign
- interfacer
- misspell
- nakedret
- scopelint
- staticcheck
- structcheck
- stylecheck
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci-actions.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- name: Linting
uses: golangci/golangci-lint-action@v2
with:
version: v1.29
version: v1.41
args: --config=./.etc/golangci.yml ./...
- name: Setup Go-${{ matrix.GOVER }}
uses: actions/setup-go@v2
Expand Down
13 changes: 1 addition & 12 deletions group/group.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,9 @@
package group

import (
"crypto/elliptic"
"encoding"
"errors"
"io"

"github.com/cloudflare/circl/ecc/p384"
)

var (
// P256 is the group generated by P-256 elliptic curve.
P256 Group = wG{elliptic.P256()}
// P384 is the group generated by P-384 elliptic curve.
P384 Group = wG{p384.P384()}
// P521 is the group generated by P-521 elliptic curve.
P521 Group = wG{elliptic.P521()}
)

type Params struct {
Expand All @@ -36,6 +24,7 @@ type Group interface {
RandomElement(io.Reader) Element
RandomScalar(io.Reader) Scalar
HashToElement(data, dst []byte) Element
HashToElementNonUniform(b, dst []byte) Element
HashToScalar(data, dst []byte) Scalar
}

Expand Down
47 changes: 10 additions & 37 deletions group/group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import (
"github.com/cloudflare/circl/internal/test"
)

var allGroups = []group.Group{
group.P256,
group.P384,
group.P521,
group.Ristretto255,
}

func TestGroup(t *testing.T) {
const testTimes = 1 << 7
for _, g := range []group.Group{
group.P256,
group.P384,
group.P521,
group.Ristretto255,
} {
for _, g := range allGroups {
g := g
n := g.(fmt.Stringer).String()
t.Run(n+"/Add", func(tt *testing.T) { testAdd(tt, testTimes, g) })
Expand Down Expand Up @@ -203,11 +205,7 @@ func testScalar(t *testing.T, testTimes int, g group.Group) {
}

func BenchmarkElement(b *testing.B) {
for _, g := range []group.Group{
group.P256,
group.P384,
group.P521,
} {
for _, g := range allGroups {
x := g.RandomElement(rand.Reader)
y := g.RandomElement(rand.Reader)
n := g.RandomScalar(rand.Reader)
Expand Down Expand Up @@ -236,11 +234,7 @@ func BenchmarkElement(b *testing.B) {
}

func BenchmarkScalar(b *testing.B) {
for _, g := range []group.Group{
group.P256,
group.P384,
group.P521,
} {
for _, g := range allGroups {
x := g.RandomScalar(rand.Reader)
y := g.RandomScalar(rand.Reader)
name := g.(fmt.Stringer).String()
Expand All @@ -261,24 +255,3 @@ func BenchmarkScalar(b *testing.B) {
})
}
}

func BenchmarkHash(b *testing.B) {
for _, g := range []group.Group{
group.P256,
group.P384,
group.P521,
} {
g := g
name := g.(fmt.Stringer).String()
b.Run(name+"/HashToElement", func(b *testing.B) {
for i := 0; i < b.N; i++ {
g.HashToElement(nil, nil)
}
})
b.Run(name+"/HashToScalar", func(b *testing.B) {
for i := 0; i < b.N; i++ {
g.HashToScalar(nil, nil)
}
})
}
}
193 changes: 193 additions & 0 deletions group/h2f/expander.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package h2f

import (
"crypto"
_ "crypto/sha256" // to link libraries
_ "crypto/sha512" // to link libraries
"encoding/binary"
"errors"
"hash"
"io"
"math"

"github.com/cloudflare/circl/xof"
)

// Expander allows to derive bytes from a slice input. This is described in
// hash to curve IETF draft.
// See https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.4
// for more details.
type Expander interface {
// Reset cleans the internal state to allow writing another input. Discards
// any input written previously.
Reset()
// Use writer to consume the input of the expander. Panics if it is invoked
// after Expand function was called.
io.Writer
// Expand fills the slice with bytes produced by the expander. Panics if
// the output's length is larger than an implementation-dependent limit.
Expand([]byte)
}

// ExpanderMD is based on a Merkle-Damgård hash function.
type ExpanderMD struct {
h crypto.Hash
dst []byte
state hash.Hash
didExpand bool
}

// NewExpanderMD returns an Expander based on a Merkle-Damgård hash function.
// The dst is a domain separation string.
func NewExpanderMD(h crypto.Hash, dst []byte) *ExpanderMD {
e := &ExpanderMD{h, dst, nil, false}
e.Reset()
return e
}

func (e *ExpanderMD) Reset() {
e.didExpand = false
if e.state == nil {
e.state = e.h.New()
} else {
e.state.Reset()
}

// preambleB0
zPad := make([]byte, e.state.BlockSize())
_, _ = e.state.Write(zPad)
}

func (e *ExpanderMD) Write(input []byte) (int, error) {
if e.didExpand {
panic(errorExpander)
}
return e.state.Write(input)
}

// Expand panics if the length of the output is longer than 255 times the
// blocksize of the hash function.
func (e *ExpanderMD) Expand(output []byte) {
bInBytes := e.h.Size()
numBlocksEll := (len(output) + bInBytes - 1) / bInBytes
if numBlocksEll > 255 {
panic(errorLongOutput)
}

if e.didExpand {
panic(errorExpander)
}

e.didExpand = true
dstPrime := e.calcDSTPrime()
libStr := [3]byte{}
binary.BigEndian.PutUint16(libStr[:2], uint16(len(output)))
_, _ = e.state.Write(libStr[:])
_, _ = e.state.Write(dstPrime)
b0 := e.state.Sum(nil)

bi := make([]byte, len(b0))
off := 0
for i := 1; i <= numBlocksEll; i++ {
for j := range b0 {
bi[j] ^= b0[j]
}
e.state.Reset()
_, _ = e.state.Write(bi)
_, _ = e.state.Write([]byte{byte(i)})
_, _ = e.state.Write(dstPrime)
bi = e.state.Sum(nil)
off += copy(output[off:], bi)
}
}

func (e *ExpanderMD) calcDSTPrime() []byte {
var dstPrime []byte
if l := len(e.dst); l > maxDSTLength {
e.state = e.h.New()
_, _ = e.state.Write(longDSTPrefix[:])
_, _ = e.state.Write(e.dst)
dstPrime = e.state.Sum(nil)
} else {
dstPrime = make([]byte, l, l+1)
copy(dstPrime, e.dst)
}
return append(dstPrime, byte(len(dstPrime)))
}

// ExpanderXOF is based on an extendable output function.
type ExpanderXOF struct {
id xof.ID
kSecLevel uint
dst []byte
state xof.XOF
didExpand bool
}

// NewExpanderXOF returns an Expander based on an extendable output function.
// The kSecLevel parameter is the target security level in bits, and dst is
// a domain separation string.
func NewExpanderXOF(id xof.ID, kSecLevel uint, dst []byte) *ExpanderXOF {
e := &ExpanderXOF{id, kSecLevel, dst, nil, false}
e.Reset()
return e
}

func (e *ExpanderXOF) Reset() {
e.didExpand = false
if e.state == nil {
e.state = e.id.New()
} else {
e.state.Reset()
}
}

func (e *ExpanderXOF) Write(input []byte) (int, error) {
if e.didExpand {
panic(errorExpander)
}
return e.state.Write(input)
}

// Expand panics if output's length is longer than 2^16 bytes.
func (e *ExpanderXOF) Expand(output []byte) {
if len(output) >= math.MaxUint16 {
panic(errorLongOutput)
}
if e.didExpand {
panic(errorExpander)
}

e.didExpand = true
dstPrime := e.calcDSTPrime()
bLen := [2]byte{}
binary.BigEndian.PutUint16(bLen[:], uint16(len(output)))
_, _ = e.state.Write(bLen[:])
_, _ = e.state.Write(dstPrime)
_, _ = io.ReadFull(e.state, output)
}

func (e *ExpanderXOF) calcDSTPrime() []byte {
var dstPrime []byte
if l := len(e.dst); l > maxDSTLength {
e.state = e.id.New()
_, _ = e.state.Write(longDSTPrefix[:])
_, _ = e.state.Write(e.dst)
max := ((2 * e.kSecLevel) + 7) / 8
dstPrime = make([]byte, max, max+1)
_, _ = io.ReadFull(e.state, dstPrime)
} else {
dstPrime = make([]byte, l, l+1)
copy(dstPrime, e.dst)
}
return append(dstPrime, byte(len(dstPrime)))
}

const maxDSTLength = 255

var (
longDSTPrefix = [17]byte{'H', '2', 'C', '-', 'O', 'V', 'E', 'R', 'S', 'I', 'Z', 'E', '-', 'D', 'S', 'T', '-'}

errorExpander = errors.New("expand function already called, reset the expander")
errorLongOutput = errors.New("requested too many bytes")
)
Loading