diff --git a/bindings/secrets.go b/bindings/secrets.go new file mode 100644 index 0000000000000000000000000000000000000000..5bdeeed03c35cf6e0af99b8a64aaf54f213e8a23 --- /dev/null +++ b/bindings/secrets.go @@ -0,0 +1,34 @@ +/////////////////////////////////////////////////////////////////////////////// +// Copyright © 2020 xx network SEZC // +// // +// Use of this source code is governed by a license that can be found in the // +// LICENSE file // +/////////////////////////////////////////////////////////////////////////////// + +package bindings + +import ( + jww "github.com/spf13/jwalterweatherman" + "gitlab.com/xx_network/crypto/csprng" +) + +// GenerateSecret creates a secret password using a system-based +// pseudorandom number generator. It takes 1 parameter, `numBytes`, +// which should be set to 32, but can be set higher in certain cases. +func GenerateSecret(numBytes int) []byte { + if numBytes < 32 { + jww.FATAL.Panicf("Secrets must have at least 32 bytes " + + "(256 bits) of entropy.") + } + + out := make([]byte, numBytes) + rng := csprng.NewSystemRNG() + numRead, err := rng.Read(out) + if err != nil { + jww.FATAL.Panicf("%+v", err) + } + if numRead != numBytes { + jww.FATAL.Panicf("Unable to read %d bytes", numBytes) + } + return out +} diff --git a/bindings/secrets_test.go b/bindings/secrets_test.go new file mode 100644 index 0000000000000000000000000000000000000000..20e1a7d51f1b182fc44df8902e85d462b615b64b --- /dev/null +++ b/bindings/secrets_test.go @@ -0,0 +1,30 @@ +//////////////////////////////////////////////////////////////////////////////////////////// +// Copyright © 2020 xx network SEZC // +// // +// Use of this source code is governed by a license that can be found in the LICENSE file // +//////////////////////////////////////////////////////////////////////////////////////////// + +package bindings + +import ( + "bytes" + "testing" +) + +func TestGenerateSecret(t *testing.T) { + secret1 := GenerateSecret(32) + secret2 := GenerateSecret(32) + + if bytes.Compare(secret1, secret2) == 0 { + t.Errorf("GenerateSecret: Not generating entropy") + } + + // This runs after the test function and errors out if no panic was + // raised. + defer func() { + if r := recover(); r == nil { + t.Errorf("GenerateSecret: Low entropy was permitted") + } + }() + GenerateSecret(31) +}