| |
| |
| |
|
|
| package drbg |
|
|
| import ( |
| "crypto/internal/fips140" |
| "crypto/internal/fips140/aes" |
| "crypto/internal/fips140/subtle" |
| "crypto/internal/fips140deps/byteorder" |
| "math/bits" |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| type Counter struct { |
| |
| c aes.CTR |
|
|
| reseedCounter uint64 |
| } |
|
|
| const ( |
| keySize = 256 / 8 |
| SeedSize = keySize + aes.BlockSize |
| reseedInterval = 1 << 48 |
| maxRequestSize = (1 << 19) / 8 |
| ) |
|
|
| func NewCounter(entropy *[SeedSize]byte) *Counter { |
| |
| fips140.RecordApproved() |
|
|
| K := make([]byte, keySize) |
| V := make([]byte, aes.BlockSize) |
|
|
| |
| |
| V[len(V)-1] = 1 |
|
|
| cipher, err := aes.New(K) |
| if err != nil { |
| panic(err) |
| } |
|
|
| c := &Counter{} |
| c.c = *aes.NewCTR(cipher, V) |
| c.update(entropy) |
| c.reseedCounter = 1 |
| return c |
| } |
|
|
| func (c *Counter) update(seed *[SeedSize]byte) { |
| |
|
|
| temp := make([]byte, SeedSize) |
| c.c.XORKeyStream(temp, seed[:]) |
| K := temp[:keySize] |
| V := temp[keySize:] |
|
|
| |
| increment((*[aes.BlockSize]byte)(V)) |
|
|
| cipher, err := aes.New(K) |
| if err != nil { |
| panic(err) |
| } |
| c.c = *aes.NewCTR(cipher, V) |
| } |
|
|
| func increment(v *[aes.BlockSize]byte) { |
| hi := byteorder.BEUint64(v[:8]) |
| lo := byteorder.BEUint64(v[8:]) |
| lo, c := bits.Add64(lo, 1, 0) |
| hi, _ = bits.Add64(hi, 0, c) |
| byteorder.BEPutUint64(v[:8], hi) |
| byteorder.BEPutUint64(v[8:], lo) |
| } |
|
|
| func (c *Counter) Reseed(entropy, additionalInput *[SeedSize]byte) { |
| |
| fips140.RecordApproved() |
|
|
| var seed [SeedSize]byte |
| subtle.XORBytes(seed[:], entropy[:], additionalInput[:]) |
| c.update(&seed) |
| c.reseedCounter = 1 |
| } |
|
|
| |
| func (c *Counter) Generate(out []byte, additionalInput *[SeedSize]byte) (reseedRequired bool) { |
| |
| fips140.RecordApproved() |
|
|
| if len(out) > maxRequestSize { |
| panic("crypto/drbg: internal error: request size exceeds maximum") |
| } |
|
|
| |
| if c.reseedCounter > reseedInterval { |
| return true |
| } |
|
|
| |
| if additionalInput != nil { |
| c.update(additionalInput) |
| } else { |
| |
| |
| |
| additionalInput = new([SeedSize]byte) |
| } |
|
|
| |
| clear(out) |
| c.c.XORKeyStream(out, out) |
| aes.RoundToBlock(&c.c) |
|
|
| |
| c.update(additionalInput) |
|
|
| |
| c.reseedCounter++ |
|
|
| |
| return false |
| } |
|
|