2019-11-21 14:24:36 +00:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
|
|
|
"encoding/hex"
|
2022-08-15 11:49:39 +00:00
|
|
|
"fmt"
|
|
|
|
"os"
|
2019-11-21 14:24:36 +00:00
|
|
|
)
|
|
|
|
|
2019-11-21 14:32:08 +00:00
|
|
|
// LoadPrivateKey allows to load private key from various formats:
|
|
|
|
// - wif string
|
|
|
|
// - hex string
|
|
|
|
// - file path (D-bytes or SEC 1 / ASN.1 DER form)
|
2019-11-21 14:24:36 +00:00
|
|
|
func LoadPrivateKey(val string) (*ecdsa.PrivateKey, error) {
|
2022-08-15 11:49:39 +00:00
|
|
|
if data, err := os.ReadFile(val); err == nil {
|
2019-11-21 14:24:36 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-08-15 11:49:39 +00:00
|
|
|
return nil, fmt.Errorf("unknown key format (%q), expect: hex-string, wif or file-path", val)
|
2019-11-21 14:24:36 +00:00
|
|
|
}
|