package shared

import (
	"crypto"
	"crypto/ed25519"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
)

func GenerateKeypair(useEd bool) (publicKey []byte, privateKey []byte, err error) {
	if useEd {
		publicKey, privateKey, err := ed25519.GenerateKey(nil)
		if err != nil {
			return nil, nil, err
		}
		publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)
		return publicKeyBytes, privateKey, nil

	} else {
		privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
		if err != nil {
			return nil, nil, err
		}
		privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
		publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
		if err != nil {
			return nil, nil, err
		}
		return publicKeyBytes, privateKeyBytes, nil
	}
}

func Sign(toSign string, keyBytes []byte, keyIsRsa bool) ([]byte, error) {
	if keyIsRsa {
		key, err := x509.ParsePKCS1PrivateKey(keyBytes)
		if err != nil {
			return nil, err
		}
		hash := sha256.Sum256([]byte(toSign))
		signed, err := key.Sign(rand.Reader, hash[:], crypto.SHA256)
		return signed, err
	} else {
		key := ed25519.PrivateKey(keyBytes)
		signed, err := key.Sign(rand.Reader, []byte(toSign), crypto.SHA256)
		return signed, err
	}
}
