drbg: fix drbg prng read issue when reseed

This commit is contained in:
Sun Yimin 2023-06-07 08:32:46 +08:00 committed by GitHub
parent 83849d33cf
commit 207fd1e7a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 2 deletions

View File

@ -166,10 +166,11 @@ func (prng *DrbgPrng) Read(data []byte) (int, error) {
} }
} else if err != nil { } else if err != nil {
return 0, err return 0, err
} } else {
total += len(b) total += len(b)
data = data[len(b):] data = data[len(b):]
} }
}
return total, nil return total, nil
} }

View File

@ -1,6 +1,7 @@
package drbg package drbg
import ( import (
"bytes"
"crypto/aes" "crypto/aes"
"crypto/sha256" "crypto/sha256"
"testing" "testing"
@ -23,6 +24,30 @@ func TestGmCtrDrbgPrng(t *testing.T) {
} }
} }
func TestGmCtrDrbgPrngReseedCase(t *testing.T) {
prng, err := NewGmCtrDrbgPrng(nil, 32, SECURITY_LEVEL_TEST, nil)
if err != nil {
t.Fatal(err)
}
data := make([]byte, 64)
for i := 0; i < int(DRBG_RESEED_COUNTER_INTERVAL_LEVEL_TEST+1); i++ {
for j := 0; j < 64; j++ {
data[j] = 0
}
n, err := prng.Read(data)
if err != nil {
t.Fatal(err)
}
if n != 64 {
t.Errorf("not got enough random bytes")
}
if bytes.Contains(data, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) {
t.Fatal("failed, it's a bug")
}
}
}
func TestNistCtrDrbgPrng(t *testing.T) { func TestNistCtrDrbgPrng(t *testing.T) {
prng, err := NewNistCtrDrbgPrng(aes.NewCipher, 16, nil, 16, SECURITY_LEVEL_TEST, nil) prng, err := NewNistCtrDrbgPrng(aes.NewCipher, 16, nil, 16, SECURITY_LEVEL_TEST, nil)
if err != nil { if err != nil {