From ba43c8bab52486e35ba5816644a014df402d37d0 Mon Sep 17 00:00:00 2001 From: Alexander Neumann Date: Wed, 1 Nov 2017 09:34:00 +0100 Subject: [PATCH] crypto: Fix nonce test, make it faster --- internal/crypto/crypto.go | 6 +++--- internal/crypto/crypto_int_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index 07ea3cc43..01cd82c45 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -237,9 +237,9 @@ var ErrInvalidCiphertext = errors.New("invalid ciphertext, same slice used for p // validNonce checks that nonce is not all zero. func validNonce(nonce []byte) bool { - sum := 0 - for b := range nonce { - sum += b + var sum byte + for _, b := range nonce { + sum |= b } return sum > 0 } diff --git a/internal/crypto/crypto_int_test.go b/internal/crypto/crypto_int_test.go index 9473d1382..769f34d1e 100644 --- a/internal/crypto/crypto_int_test.go +++ b/internal/crypto/crypto_int_test.go @@ -163,3 +163,30 @@ func TestCrypto(t *testing.T) { } } } + +func TestNonceVadlid(t *testing.T) { + nonce := make([]byte, ivSize) + + if validNonce(nonce) { + t.Error("null nonce detected as valid") + } + + for i := 0; i < 100; i++ { + nonce = NewRandomNonce() + if !validNonce(nonce) { + t.Errorf("random nonce not detected as valid: %02x", nonce) + } + } +} + +func BenchmarkNonceValid(b *testing.B) { + nonce := NewRandomNonce() + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + if !validNonce(nonce) { + b.Fatal("nonce is invalid") + } + } +}