2021-05-25 19:59:21 +00:00
|
|
|
package hcs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/curve25519"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
2021-05-26 18:23:36 +00:00
|
|
|
// Credentials is an HCS interface (private/public key).
|
2021-05-25 19:59:21 +00:00
|
|
|
Credentials interface {
|
|
|
|
PublicKey() PublicKey
|
|
|
|
PrivateKey() PrivateKey
|
|
|
|
}
|
|
|
|
|
|
|
|
keyer interface {
|
|
|
|
io.WriterTo
|
|
|
|
|
|
|
|
Bytes() []byte
|
|
|
|
String() string
|
|
|
|
}
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// PublicKey is a public key wrapper providing useful methods.
|
2021-05-25 19:59:21 +00:00
|
|
|
PublicKey interface {
|
|
|
|
keyer
|
|
|
|
}
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// PrivateKey is private key wrapper providing useful methods.
|
2021-05-25 19:59:21 +00:00
|
|
|
PrivateKey interface {
|
|
|
|
keyer
|
|
|
|
|
|
|
|
PublicKey() PublicKey
|
|
|
|
}
|
|
|
|
|
|
|
|
credentials struct {
|
|
|
|
public PublicKey
|
|
|
|
secret PrivateKey
|
|
|
|
}
|
|
|
|
|
|
|
|
public []byte
|
|
|
|
secret []byte
|
|
|
|
)
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// ErrEmptyCredentials is returned when no credentials are provided.
|
2021-05-25 19:59:21 +00:00
|
|
|
var ErrEmptyCredentials = errors.New("empty credentials")
|
|
|
|
|
|
|
|
var _ = NewCredentials
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// Generate generates new key pair using given source of randomness.
|
2021-05-25 19:59:21 +00:00
|
|
|
func Generate(r io.Reader) (Credentials, error) {
|
|
|
|
buf := make([]byte, curve25519.ScalarSize)
|
|
|
|
|
|
|
|
if _, err := r.Read(buf); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
sk := secret(buf)
|
|
|
|
return &credentials{
|
|
|
|
secret: &sk,
|
|
|
|
public: sk.PublicKey(),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// NewCredentials loads private key from the string given and returns Credentials wrapper.
|
2021-05-25 19:59:21 +00:00
|
|
|
func NewCredentials(val string) (Credentials, error) {
|
|
|
|
if val == "" {
|
|
|
|
return nil, ErrEmptyCredentials
|
|
|
|
}
|
|
|
|
|
|
|
|
sk, err := loadPrivateKey(val)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &credentials{
|
|
|
|
secret: sk,
|
|
|
|
public: sk.PublicKey(),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// PublicKey returns public key.
|
2021-05-25 19:59:21 +00:00
|
|
|
func (c *credentials) PublicKey() PublicKey {
|
|
|
|
return c.public
|
|
|
|
}
|
|
|
|
|
2021-05-26 18:23:36 +00:00
|
|
|
// PrivateKey returns private key.
|
2021-05-25 19:59:21 +00:00
|
|
|
func (c *credentials) PrivateKey() PrivateKey {
|
|
|
|
return c.secret
|
|
|
|
}
|