Add method to load PrivateKey

- from hex string
- from wif format
- from file path
This commit is contained in:
Evgeniy Kulikov 2019-11-21 17:24:36 +03:00
parent 5a95565a67
commit d059767e79
No known key found for this signature in database
GPG key ID: BF6AEE0A2A699BF2
2 changed files with 107 additions and 0 deletions

21
load.go Normal file
View file

@ -0,0 +1,21 @@
package crypto
import (
"crypto/ecdsa"
"encoding/hex"
"io/ioutil"
"github.com/pkg/errors"
)
func LoadPrivateKey(val string) (*ecdsa.PrivateKey, error) {
if data, err := ioutil.ReadFile(val); err == nil {
return UnmarshalPrivateKey(data)
} else if data, err = hex.DecodeString(val); err == nil {
return UnmarshalPrivateKey(data)
} else if key, err := WIFDecode(val); err == nil {
return key, nil
}
return nil, errors.Errorf("unknown key format (%q), expect: hex-string, wif or file-path", val)
}

86
load_test.go Normal file
View file

@ -0,0 +1,86 @@
package crypto
import (
"crypto/x509"
"encoding/hex"
"io/ioutil"
"os"
"testing"
"github.com/nspcc-dev/neofs-crypto/test"
"github.com/stretchr/testify/require"
)
func Test_LoadPrivateKey_FromWIF(t *testing.T) {
for i := 0; i < 10; i++ {
expected := test.DecodeKey(i)
wif, err := WIFEncode(expected)
require.NoError(t, err)
actual, err := LoadPrivateKey(wif)
require.NoError(t, err)
require.Equal(t, expected, actual)
}
}
func Test_LoadPrivateKey_FromHexString(t *testing.T) {
for i := 0; i < 10; i++ {
expected := test.DecodeKey(i)
hs := hex.EncodeToString(expected.D.Bytes())
actual, err := LoadPrivateKey(hs)
require.NoError(t, err)
require.Equal(t, expected, actual)
}
}
func Test_LoadPrivateKey_FromFile(t *testing.T) {
for i := 0; i < 10; i++ {
expected := test.DecodeKey(i)
file, err := ioutil.TempFile("", "_marshaled.key")
require.NoError(t, err)
defer func() {
require.NoError(t, file.Close())
require.NoError(t, os.Remove(file.Name()))
}()
data, err := x509.MarshalECPrivateKey(expected)
require.NoError(t, err)
_, err = file.Write(data)
require.NoError(t, err)
actual, err := LoadPrivateKey(file.Name())
require.NoError(t, err)
require.Equal(t, expected, actual)
}
}
func Test_LoadPrivateKey_FromCompressedFormatFile(t *testing.T) {
for i := 0; i < 10; i++ {
expected := test.DecodeKey(i)
file, err := ioutil.TempFile("", "_compressed.key")
require.NoError(t, err)
defer func() {
require.NoError(t, file.Close())
require.NoError(t, os.Remove(file.Name()))
}()
_, err = file.Write(expected.D.Bytes())
require.NoError(t, err)
actual, err := LoadPrivateKey(file.Name())
require.NoError(t, err)
require.Equal(t, expected, actual)
}
}