From 1c399522c9d4869f327fa3348b8da88914d57ca3 Mon Sep 17 00:00:00 2001 From: "Richard T. Carback III" <rick.carback@gmail.com> Date: Wed, 14 Jul 2021 20:32:40 +0000 Subject: [PATCH] Add GenerateSecret helper function --- bindings/secrets.go | 34 ++++++++++++++++++++++++++++++++++ bindings/secrets_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 bindings/secrets.go create mode 100644 bindings/secrets_test.go diff --git a/bindings/secrets.go b/bindings/secrets.go new file mode 100644 index 000000000..5bdeeed03 --- /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 000000000..20e1a7d51 --- /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) +} -- GitLab