From 49b3026574ab692cfabcabe90751b163a76df31b Mon Sep 17 00:00:00 2001 From: Joe Richey Date: Thu, 2 Mar 2017 11:58:07 -0800 Subject: 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 --- crypto/crypto_test.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'crypto/crypto_test.go') 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() +} -- cgit v1.2.3