2021-03-30 22:46:33 +00:00
|
|
|
package neofs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
2021-04-14 19:57:58 +00:00
|
|
|
"crypto/elliptic"
|
|
|
|
"crypto/rand"
|
|
|
|
"math/big"
|
2021-03-30 22:46:33 +00:00
|
|
|
|
|
|
|
"github.com/nspcc-dev/neofs-api-go/pkg/owner"
|
|
|
|
crypto "github.com/nspcc-dev/neofs-crypto"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
// Credentials contains methods that needed to work with NeoFS.
|
|
|
|
Credentials interface {
|
|
|
|
Owner() *owner.ID
|
|
|
|
PublicKey() *ecdsa.PublicKey
|
|
|
|
PrivateKey() *ecdsa.PrivateKey
|
|
|
|
}
|
|
|
|
|
2021-03-31 19:08:39 +00:00
|
|
|
credentials struct {
|
|
|
|
key *ecdsa.PrivateKey
|
|
|
|
ownerID *owner.ID
|
2021-03-30 22:46:33 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2021-05-13 12:22:03 +00:00
|
|
|
// NewCredentials creates an instance of Credentials through string
|
|
|
|
// representation of secret. It allows passing WIF, path, hex-encoded and others.
|
2021-03-30 22:46:33 +00:00
|
|
|
func NewCredentials(secret string) (Credentials, error) {
|
|
|
|
key, err := crypto.LoadPrivateKey(secret)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return setFromPrivateKey(key)
|
|
|
|
}
|
|
|
|
|
2021-04-14 19:57:58 +00:00
|
|
|
// NewEphemeralCredentials creates new private key and Credentials based on that
|
|
|
|
// key.
|
|
|
|
func NewEphemeralCredentials() (Credentials, error) {
|
|
|
|
c := elliptic.P256()
|
|
|
|
priv, x, y, err := elliptic.GenerateKey(c, rand.Reader)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
key := &ecdsa.PrivateKey{
|
|
|
|
PublicKey: ecdsa.PublicKey{
|
|
|
|
Curve: c,
|
|
|
|
X: x,
|
|
|
|
Y: y,
|
|
|
|
},
|
|
|
|
D: new(big.Int).SetBytes(priv),
|
|
|
|
}
|
|
|
|
return setFromPrivateKey(key)
|
|
|
|
}
|
|
|
|
|
2021-03-30 22:46:33 +00:00
|
|
|
// PrivateKey returns ecdsa.PrivateKey.
|
2021-03-31 19:08:39 +00:00
|
|
|
func (c *credentials) PrivateKey() *ecdsa.PrivateKey {
|
2021-03-30 22:46:33 +00:00
|
|
|
return c.key
|
|
|
|
}
|
|
|
|
|
|
|
|
// PublicKey returns ecdsa.PublicKey.
|
2021-03-31 19:08:39 +00:00
|
|
|
func (c *credentials) PublicKey() *ecdsa.PublicKey {
|
2021-03-30 22:46:33 +00:00
|
|
|
return &c.key.PublicKey
|
|
|
|
}
|
|
|
|
|
|
|
|
// Owner returns owner.ID.
|
2021-03-31 19:08:39 +00:00
|
|
|
func (c *credentials) Owner() *owner.ID {
|
|
|
|
return c.ownerID
|
2021-03-30 22:46:33 +00:00
|
|
|
}
|
|
|
|
|
2021-03-31 19:08:39 +00:00
|
|
|
func setFromPrivateKey(key *ecdsa.PrivateKey) (*credentials, error) {
|
2021-03-30 22:46:33 +00:00
|
|
|
wallet, err := owner.NEO3WalletFromPublicKey(&key.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ownerID := owner.NewIDFromNeo3Wallet(wallet)
|
2021-04-14 19:59:12 +00:00
|
|
|
return &credentials{key: key, ownerID: ownerID}, nil
|
2021-03-30 22:46:33 +00:00
|
|
|
}
|