diff options
| author | Joe Richey <joerichey@google.com> | 2017-03-02 11:58:07 -0800 |
|---|---|---|
| committer | Joe Richey joerichey@google.com <joerichey@google.com> | 2017-05-02 13:39:18 -0700 |
| commit | 49b3026574ab692cfabcabe90751b163a76df31b (patch) | |
| tree | c638076dd5faeadf84afd49fcf15728f68181eba /crypto/crypto_test.go | |
| parent | 53d15f466a665e4e564af3afdcbcfe9ff1c91331 (diff) | |
crypto: add secure random reader using getrandom
This commit adds in RandReader, a cryptographically secure io.Reader
that will fail when the os has insufficient randomness. This is done
using the getrandom() syscall in non-blocking mode.
see: http://man7.org/linux/man-pages/man2/getrandom.2.html
Any kernel new enough to have filesystem encryption will also have this
syscall.
This RandReader is preferable to the one provided by the standard
library in crypto/rand. See the bugs:
https://github.com/golang/go/issues/11833
https://github.com/golang/go/issues/19274
This will be removed when go updates the crypto/rand implementation.
Change-Id: Icccaf07bc6011b95cd31a5c268e7486807dcffe2
Diffstat (limited to 'crypto/crypto_test.go')
| -rw-r--r-- | crypto/crypto_test.go | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go index 025b5b9..7447e40 100644 --- a/crypto/crypto_test.go +++ b/crypto/crypto_test.go @@ -21,6 +21,7 @@ package crypto import ( "bytes" + "compress/zlib" "os" "testing" ) @@ -139,3 +140,33 @@ func TestBadAddKeys(t *testing.T) { t.Error("InsertPolicyKey should fail with bad service") } } + +// Check that we can create random keys. All this test does to test the +// "randomness" is generate a page of random bytes and attempts compression. +// If the data can be compressed it is probably not very random. This isn't +// indented to be a sufficient test for randomness (which is impossible), but a +// way to catch simple regressions (key is all zeros or contains a repeating +// pattern). +func TestRandomKeyGen(t *testing.T) { + key, err := NewRandomKey(os.Getpagesize()) + if err != nil { + t.Fatal(err) + } + defer key.Wipe() + + if didCompress(key.data) { + t.Errorf("Random key (%d bytes) should not be compressible", key.Len()) + } +} + +// didCompress checks if the given data can be compressed. Specifically, it +// returns true if running zlib on the provided input produces a shorter output. +func didCompress(input []byte) bool { + var output bytes.Buffer + + w := zlib.NewWriter(&output) + _, err := w.Write(input) + w.Close() + + return err == nil && len(input) > output.Len() +} |