github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/pkg/crypto/ed25519/ed25519.go (about)

     1  package ed25519
     2  
     3  import (
     4  	"crypto/ed25519"
     5  	"crypto/rand"
     6  	"encoding/base64"
     7  
     8  	"github.com/kubri/kubri/pkg/crypto"
     9  )
    10  
    11  type (
    12  	PrivateKey = ed25519.PrivateKey
    13  	PublicKey  = ed25519.PublicKey
    14  )
    15  
    16  // Sign signs the data with the private key.
    17  func Sign(key PrivateKey, data []byte) ([]byte, error) {
    18  	if l := len(key); l != ed25519.PrivateKeySize {
    19  		return nil, crypto.ErrInvalidKey
    20  	}
    21  	return ed25519.Sign(key, data), nil
    22  }
    23  
    24  // Verify verifies the signature of the data with the public key.
    25  func Verify(key PublicKey, data, sig []byte) bool {
    26  	if l := len(key); l != ed25519.PublicKeySize {
    27  		return false
    28  	}
    29  	return ed25519.Verify(key, data, sig)
    30  }
    31  
    32  // NewPrivateKey returns a new private key.
    33  func NewPrivateKey() (PrivateKey, error) {
    34  	_, key, err := ed25519.GenerateKey(rand.Reader)
    35  	return key, err
    36  }
    37  
    38  // MarshalPrivateKey returns the base64 encoded private key.
    39  func MarshalPrivateKey(key PrivateKey) ([]byte, error) {
    40  	return marshal(key, ed25519.PrivateKeySize)
    41  }
    42  
    43  // UnmarshalPrivateKey returns a private key from a base64 encoded key.
    44  func UnmarshalPrivateKey(b []byte) (PrivateKey, error) {
    45  	return unmarshal(b, ed25519.PrivateKeySize)
    46  }
    47  
    48  // Public extracts the public key from a private key.
    49  func Public(key PrivateKey) PublicKey {
    50  	return key.Public().(PublicKey) //nolint:forcetypeassert
    51  }
    52  
    53  // MarshalPublicKey returns the base64 encoded public key.
    54  func MarshalPublicKey(key PublicKey) ([]byte, error) {
    55  	return marshal(key, ed25519.PublicKeySize)
    56  }
    57  
    58  // UnmarshalPublicKey returns a public key from a base64 encoded key.
    59  func UnmarshalPublicKey(b []byte) (PublicKey, error) {
    60  	return unmarshal(b, ed25519.PublicKeySize)
    61  }
    62  
    63  func marshal(key []byte, size int) ([]byte, error) {
    64  	if len(key) != size {
    65  		return nil, crypto.ErrInvalidKey
    66  	}
    67  	b := make([]byte, base64.StdEncoding.EncodedLen(size))
    68  	base64.StdEncoding.Encode(b, key)
    69  	return b, nil
    70  }
    71  
    72  func unmarshal(b []byte, size int) ([]byte, error) {
    73  	key := make([]byte, base64.StdEncoding.DecodedLen(len(b)))
    74  	n, err := base64.StdEncoding.Decode(key, b)
    75  	if err != nil || n != size {
    76  		return nil, crypto.ErrInvalidKey
    77  	}
    78  	return key[:n], nil
    79  }