Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
func TestHMACTotalTiming(t *testing.T) {
sumData := make(plotter.XYs, 256)
constData := make(plotter.XYs, 256)
naiveData := make(plotter.XYs, 256)
data := []byte("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789")
sumBuf := make([]byte, 0, 100)
for n := 0; n < 256; n++ {
var res1, res2 []byte
ns := testing.Benchmark(func(b *testing.B) {
h := hmac.New(newConstantTimeHash(sha1.New), make([]byte, 30))
for i := 0; i < b.N; i++ {
h.Reset()
h.Write(data[:len(data)-n])
res1 = h.Sum(sumBuf)
h.Write(data[len(data)-n:])
}
}).NsPerOp()
t.Logf("ConstantTimeHash %d bytes: %d ns/op", n, ns)
constData[n].X = float64(len(data) - n)
constData[n].Y = float64(ns)
ns = testing.Benchmark(func(b *testing.B) {
h := hmac.New(sha1.New, make([]byte, 30))
for i := 0; i < b.N; i++ {
h.Reset()
h.Write(data[:len(data)-n])
res2 = h.Sum(sumBuf)
}
}).NsPerOp()
t.Logf("Sum %d bytes: %d ns/op", n, ns)
sumData[n].X = float64(len(data) - n)
sumData[n].Y = float64(ns)
ns = testing.Benchmark(func(b *testing.B) {
h := hmac.New(sha1.New, make([]byte, 30))
for i := 0; i < b.N; i++ {
h.Reset()
h.Write(data[:len(data)-n])
res2 = h.Sum(sumBuf)
h.Write(data[len(data)-n:])
}
}).NsPerOp()
t.Logf("Sum+Write %d bytes: %d ns/op", n, ns)
naiveData[n].X = float64(len(data) - n)
naiveData[n].Y = float64(ns)
if !bytes.Equal(res1, res2) {
t.Errorf("different output at length %d", n)
}
}
p, err := plot.New()
if err != nil {
panic(err)
}
p.Title.Text = "HMAC timings"
p.X.Label.Text = "First Write() bytes"
p.Y.Label.Text = "ns"
s, err := plotter.NewScatter(sumData)
if err != nil {
panic(err)
}
c, err := plotter.NewScatter(constData)
if err != nil {
panic(err)
}
c.GlyphStyle.Shape = draw.PyramidGlyph{}
c.GlyphStyle.Color = color.RGBA{R: 255, A: 255}
x, err := plotter.NewScatter(naiveData)
if err != nil {
panic(err)
}
x.GlyphStyle.Shape = draw.CrossGlyph{}
x.GlyphStyle.Color = color.RGBA{R: 255, A: 255}
p.Add(s, c, x)
if err := p.Save(297*vg.Millimeter, 210*vg.Millimeter, "hmac.png"); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment