2020-11-12 14:18:30 +00:00
|
|
|
package ed25519
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ed25519"
|
|
|
|
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
|
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
|
|
|
|
|
|
|
"github.com/Secured-Finance/dione/sigs"
|
|
|
|
"github.com/Secured-Finance/dione/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ed25519Signer struct{}
|
|
|
|
|
|
|
|
func (ed25519Signer) GenPrivate() ([]byte, error) {
|
|
|
|
_, privKey, err := ed25519.GenerateKey(nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return privKey.Seed(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ed25519Signer) ToPublic(priv []byte) ([]byte, error) {
|
2020-11-15 05:59:46 +00:00
|
|
|
var privKey ed25519.PrivateKey = priv
|
2020-11-12 14:18:30 +00:00
|
|
|
pubKey := privKey.Public().(ed25519.PublicKey)
|
|
|
|
return pubKey, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ed25519Signer) Sign(p []byte, msg []byte) ([]byte, error) {
|
2020-11-15 05:59:46 +00:00
|
|
|
var privKey ed25519.PrivateKey = p
|
2020-11-12 14:18:30 +00:00
|
|
|
return ed25519.Sign(privKey, msg), nil
|
|
|
|
}
|
|
|
|
|
2020-12-02 14:03:39 +00:00
|
|
|
func (ed25519Signer) Verify(sig []byte, a []byte, msg []byte) error {
|
|
|
|
id, err := peer.IDFromBytes(a)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
pubKey, err := id.ExtractPublicKey()
|
2020-11-12 14:18:30 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-11-20 21:29:30 +00:00
|
|
|
pKeyRaw, err := pubKey.Raw()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if valid := ed25519.Verify(pKeyRaw, msg, sig); !valid {
|
2020-11-12 14:18:30 +00:00
|
|
|
return xerrors.Errorf("failed to verify signature")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
sigs.RegisterSignature(types.SigTypeEd25519, ed25519Signer{})
|
|
|
|
}
|