github.com/jasoet/gopki@v1.15.0/keypair/algo/ed25519.go (about)

     1  package algo
     2  
     3  import (
     4  	"crypto/ed25519"
     5  	"crypto/rand"
     6  	"crypto/x509"
     7  	"encoding/pem"
     8  	"fmt"
     9  	"github.com/jasoet/gopki/keypair/format"
    10  	"strings"
    11  
    12  	"golang.org/x/crypto/ssh"
    13  )
    14  
    15  // Ed25519Config represents the configuration for Ed25519 key generation.
    16  // Ed25519 has no configurable parameters, so this is used as a placeholder for generic constraints.
    17  type Ed25519Config string
    18  
    19  const Ed25519Default = Ed25519Config("")
    20  
    21  // Ed25519KeyPair represents a generated Ed25519 key pair containing both private and public keys.
    22  // Ed25519 keys are fixed-length and offer high security with excellent performance.
    23  type Ed25519KeyPair struct {
    24  	PrivateKey ed25519.PrivateKey // The Ed25519 private key (64 bytes)
    25  	PublicKey  ed25519.PublicKey  // The corresponding Ed25519 public key (32 bytes)
    26  }
    27  
    28  // GenerateEd25519KeyPair generates a new Ed25519 key pair.
    29  // Ed25519 is a modern elliptic curve signature algorithm that provides:
    30  //   - High security (equivalent to ~3072-bit RSA)
    31  //   - Fast key generation, signing, and verification
    32  //   - Small key sizes (32-byte public keys, 64-byte private keys)
    33  //   - Immunity to timing attacks
    34  //
    35  // Returns:
    36  //   - *Ed25519KeyPair: The generated key pair
    37  //   - error: Error if key generation fails
    38  //
    39  // Security considerations:
    40  //   - Uses crypto/rand.Reader for secure random number generation
    41  //   - No configurable parameters - the algorithm is designed to be secure by default
    42  //   - Recommended for new applications requiring digital signatures
    43  //
    44  // Example:
    45  //
    46  //	keyPair, err := GenerateEd25519KeyPair()
    47  //	if err != nil {
    48  //		log.Printf("Ed25519 key generation failed: %v", err)
    49  //	}
    50  func GenerateEd25519KeyPair() (*Ed25519KeyPair, error) {
    51  	publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
    52  	if err != nil {
    53  		return nil, fmt.Errorf("failed to generate Ed25519 key pair: %w", err)
    54  	}
    55  
    56  	return &Ed25519KeyPair{
    57  		PrivateKey: privateKey,
    58  		PublicKey:  publicKey,
    59  	}, nil
    60  }
    61  
    62  // PrivateKeyToPEM converts the Ed25519 private key to PEM format using PKCS#8 encoding.
    63  // PKCS#8 format ensures compatibility with standard cryptographic tools and libraries.
    64  //
    65  // Returns:
    66  //   - PEM: PEM-encoded private key data
    67  //   - error: Error if marshaling or encoding fails
    68  //
    69  // The returned PEM block will have type "PRIVATE KEY" and contain the
    70  // PKCS#8 encoded private key data.
    71  //
    72  // Example:
    73  //
    74  //	pemData, err := keyPair.PrivateKeyToPEM()
    75  //	if err != nil {
    76  //		log.Printf("Private key PEM conversion failed: %v", err)
    77  //	}
    78  func (kp *Ed25519KeyPair) PrivateKeyToPEM() (format.PEM, error) {
    79  	privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(kp.PrivateKey)
    80  	if err != nil {
    81  		return nil, fmt.Errorf("failed to marshal private key: %w", err)
    82  	}
    83  
    84  	privateKeyPEM := pem.EncodeToMemory(&pem.Block{
    85  		Type:  "PRIVATE KEY",
    86  		Bytes: privateKeyBytes,
    87  	})
    88  
    89  	return privateKeyPEM, nil
    90  }
    91  
    92  // PublicKeyToPEM converts the Ed25519 public key to PEM format using PKIX encoding.
    93  // PKIX format is the standard format for public key encoding in X.509 certificates.
    94  //
    95  // Returns:
    96  //   - PEM: PEM-encoded public key data
    97  //   - error: Error if marshaling or encoding fails
    98  //
    99  // The returned PEM block will have type "PUBLIC KEY" and contain the
   100  // PKIX encoded public key data.
   101  //
   102  // Example:
   103  //
   104  //	pemData, err := keyPair.PublicKeyToPEM()
   105  //	if err != nil {
   106  //		log.Printf("Public key PEM conversion failed: %v", err)
   107  //	}
   108  func (kp *Ed25519KeyPair) PublicKeyToPEM() (format.PEM, error) {
   109  	publicKeyBytes, err := x509.MarshalPKIXPublicKey(kp.PublicKey)
   110  	if err != nil {
   111  		return nil, fmt.Errorf("failed to marshal public key: %w", err)
   112  	}
   113  
   114  	publicKeyPEM := pem.EncodeToMemory(&pem.Block{
   115  		Type:  "PUBLIC KEY",
   116  		Bytes: publicKeyBytes,
   117  	})
   118  
   119  	return publicKeyPEM, nil
   120  }
   121  
   122  // Ed25519KeyPairFromPEM reconstructs an Ed25519 key pair from PEM-encoded private key data.
   123  // The function parses the private key and derives the public key from it.
   124  //
   125  // Parameters:
   126  //   - privateKeyPEM: PEM-encoded private key data in PKCS#8 format
   127  //
   128  // Returns:
   129  //   - *Ed25519KeyPair: The reconstructed key pair
   130  //   - error: Error if PEM decoding, parsing, or type assertion fails
   131  //
   132  // The function expects the PEM block to contain a PKCS#8 encoded private key.
   133  // It will validate that the key is actually an Ed25519 key before returning.
   134  // The public key is derived directly from the private key.
   135  //
   136  // Example:
   137  //
   138  //	keyPair, err := Ed25519KeyPairFromPEM(pemData)
   139  //	if err != nil {
   140  //		log.Printf("Failed to reconstruct Ed25519 key pair: %v", err)
   141  //	}
   142  func Ed25519KeyPairFromPEM(privateKeyPEM format.PEM) (*Ed25519KeyPair, error) {
   143  	block, _ := pem.Decode(privateKeyPEM)
   144  	if block == nil {
   145  		return nil, fmt.Errorf("failed to decode PEM block")
   146  	}
   147  
   148  	privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
   149  	if err != nil {
   150  		return nil, fmt.Errorf("failed to parse private key: %w", err)
   151  	}
   152  
   153  	ed25519PrivateKey, ok := privateKey.(ed25519.PrivateKey)
   154  	if !ok {
   155  		return nil, fmt.Errorf("private key is not an Ed25519 key")
   156  	}
   157  
   158  	publicKey := ed25519PrivateKey.Public().(ed25519.PublicKey)
   159  
   160  	return &Ed25519KeyPair{
   161  		PrivateKey: ed25519PrivateKey,
   162  		PublicKey:  publicKey,
   163  	}, nil
   164  }
   165  
   166  // PrivateKeyToDER converts the Ed25519 private key to DER (Distinguished Encoding Rules) format.
   167  // DER is a binary format that is more compact than PEM and faster to parse.
   168  //
   169  // Returns:
   170  //   - DER: DER-encoded private key data
   171  //   - error: Error if marshaling fails
   172  //
   173  // The function uses PKCS#8 encoding for maximum compatibility across different systems.
   174  // DER format is typically 30% smaller than equivalent PEM format.
   175  //
   176  // Example:
   177  //
   178  //	derData, err := keyPair.PrivateKeyToDER()
   179  //	if err != nil {
   180  //		log.Printf("DER conversion failed: %v", err)
   181  //	}
   182  func (kp *Ed25519KeyPair) PrivateKeyToDER() (format.DER, error) {
   183  	derBytes, err := x509.MarshalPKCS8PrivateKey(kp.PrivateKey)
   184  	if err != nil {
   185  		return nil, fmt.Errorf("failed to marshal private key to DER: %w", err)
   186  	}
   187  	return derBytes, nil
   188  }
   189  
   190  // PublicKeyToDER converts the Ed25519 public key to DER (Distinguished Encoding Rules) format.
   191  // DER is a binary format that provides compact storage and fast parsing.
   192  //
   193  // Returns:
   194  //   - []byte: DER-encoded public key data
   195  //   - error: Error if marshaling fails
   196  //
   197  // The function uses PKIX encoding for standard compatibility.
   198  // DER format is the binary equivalent of PEM without Base64 encoding and headers.
   199  //
   200  // Example:
   201  //
   202  //	derData, err := keyPair.PublicKeyToDER()
   203  //	if err != nil {
   204  //		log.Printf("DER conversion failed: %v", err)
   205  //	}
   206  func (kp *Ed25519KeyPair) PublicKeyToDER() (format.DER, error) {
   207  	derBytes, err := x509.MarshalPKIXPublicKey(kp.PublicKey)
   208  	if err != nil {
   209  		return nil, fmt.Errorf("failed to marshal public key to DER: %w", err)
   210  	}
   211  	return derBytes, nil
   212  }
   213  
   214  // PublicKeyToSSH converts the Ed25519 public key to SSH public key format.
   215  // The SSH format is used in authorized_keys files and for key identification.
   216  //
   217  // Parameters:
   218  //   - comment: Optional comment to include in the SSH key (commonly username@hostname)
   219  //
   220  // Returns:
   221  //   - SSH: SSH public key in format "ssh-ed25519 base64-key [comment]"
   222  //   - error: Error if conversion fails
   223  //
   224  // Example:
   225  //
   226  //	sshKey, err := keyPair.PublicKeyToSSH("user@example.com")
   227  //	if err != nil {
   228  //		log.Printf("SSH conversion failed: %v", err)
   229  //	}
   230  func (kp *Ed25519KeyPair) PublicKeyToSSH(comment string) (format.SSH, error) {
   231  	sshPubKey, err := ssh.NewPublicKey(kp.PublicKey)
   232  	if err != nil {
   233  		return "", fmt.Errorf("failed to convert to SSH public key: %w", err)
   234  	}
   235  
   236  	sshData := ssh.MarshalAuthorizedKey(sshPubKey)
   237  	sshStr := strings.TrimSpace(string(sshData))
   238  
   239  	// Add comment if provided and not already present
   240  	if comment != "" && !strings.Contains(sshStr, comment) {
   241  		parts := strings.SplitN(sshStr, " ", 3)
   242  		if len(parts) >= 2 {
   243  			sshStr = parts[0] + " " + parts[1] + " " + comment
   244  		}
   245  	}
   246  
   247  	return format.SSH(sshStr), nil
   248  }
   249  
   250  // PrivateKeyToSSH converts the Ed25519 private key to OpenSSH private key format.
   251  // This format is used by OpenSSH for storing private keys, with optional passphrase protection.
   252  //
   253  // Parameters:
   254  //   - comment: Optional comment to embed in the key file
   255  //   - passphrase: Optional passphrase for key encryption (empty string for unencrypted)
   256  //
   257  // Returns:
   258  //   - SSH: OpenSSH private key in PEM-like format
   259  //   - error: Error if conversion fails
   260  //
   261  // Security note: Using a passphrase is recommended for private key storage.
   262  //
   263  // Example:
   264  //
   265  //	sshKey, err := keyPair.PrivateKeyToSSH("my-key", "secure-passphrase")
   266  //	if err != nil {
   267  //		log.Printf("SSH conversion failed: %v", err)
   268  //	}
   269  func (kp *Ed25519KeyPair) PrivateKeyToSSH(comment string, passphrase string) (format.SSH, error) {
   270  	var pemBlock *pem.Block
   271  	var err error
   272  
   273  	if passphrase == "" {
   274  		pemBlock, err = ssh.MarshalPrivateKey(kp.PrivateKey, comment)
   275  	} else {
   276  		pemBlock, err = ssh.MarshalPrivateKeyWithPassphrase(kp.PrivateKey, comment, []byte(passphrase))
   277  	}
   278  
   279  	if err != nil {
   280  		return "", fmt.Errorf("failed to marshal SSH private key: %w", err)
   281  	}
   282  
   283  	sshPrivateKey := pem.EncodeToMemory(pemBlock)
   284  	return format.SSH(sshPrivateKey), nil
   285  }
   286  
   287  // Ed25519KeyPairFromDER reconstructs an Ed25519 key pair from DER-encoded private key data.
   288  // The function parses the private key and derives the public key from it.
   289  //
   290  // Parameters:
   291  //   - privateKeyDER: DER-encoded private key data in PKCS#8 format
   292  //
   293  // Returns:
   294  //   - *Ed25519KeyPair: The reconstructed key pair
   295  //   - error: Error if parsing or type assertion fails
   296  //
   297  // The function expects the DER data to contain a PKCS#8 encoded private key.
   298  // It will validate that the key is actually an Ed25519 key before returning.
   299  // The public key is derived directly from the private key.
   300  //
   301  // Example:
   302  //
   303  //	keyPair, err := Ed25519KeyPairFromDER(derData)
   304  //	if err != nil {
   305  //		log.Printf("Failed to reconstruct Ed25519 key pair from DER: %v", err)
   306  //	}
   307  func Ed25519KeyPairFromDER(privateKeyDER format.DER) (*Ed25519KeyPair, error) {
   308  	privateKey, err := x509.ParsePKCS8PrivateKey(privateKeyDER)
   309  	if err != nil {
   310  		return nil, fmt.Errorf("failed to parse DER private key: %w", err)
   311  	}
   312  
   313  	ed25519PrivateKey, ok := privateKey.(ed25519.PrivateKey)
   314  	if !ok {
   315  		return nil, fmt.Errorf("private key is not an Ed25519 key")
   316  	}
   317  
   318  	publicKey := ed25519PrivateKey.Public().(ed25519.PublicKey)
   319  
   320  	return &Ed25519KeyPair{
   321  		PrivateKey: ed25519PrivateKey,
   322  		PublicKey:  publicKey,
   323  	}, nil
   324  }
   325  
   326  // Ed25519KeyPairFromSSH reconstructs an Ed25519 key pair from SSH-encoded private key data.
   327  // The function parses the SSH private key and derives the public key from it.
   328  //
   329  // Parameters:
   330  //   - privateKeySSH: SSH-encoded private key data in OpenSSH format
   331  //   - passphrase: Passphrase for encrypted keys (empty string for unencrypted)
   332  //
   333  // Returns:
   334  //   - *Ed25519KeyPair: The reconstructed key pair
   335  //   - error: Error if parsing, decryption, or type assertion fails
   336  //
   337  // The function expects the SSH data to contain an OpenSSH formatted private key.
   338  // It will validate that the key is actually an Ed25519 key before returning.
   339  // The public key is derived directly from the private key.
   340  //
   341  // Example:
   342  //
   343  //	keyPair, err := Ed25519KeyPairFromSSH(sshData, "passphrase")
   344  //	if err != nil {
   345  //		log.Printf("Failed to reconstruct Ed25519 key pair from SSH: %v", err)
   346  //	}
   347  func Ed25519KeyPairFromSSH(privateKeySSH format.SSH, passphrase string) (*Ed25519KeyPair, error) {
   348  	var rawKey interface{}
   349  	var err error
   350  
   351  	if passphrase == "" {
   352  		rawKey, err = ssh.ParseRawPrivateKey([]byte(privateKeySSH))
   353  	} else {
   354  		rawKey, err = ssh.ParseRawPrivateKeyWithPassphrase([]byte(privateKeySSH), []byte(passphrase))
   355  	}
   356  
   357  	if err != nil {
   358  		return nil, fmt.Errorf("failed to parse SSH private key: %w", err)
   359  	}
   360  
   361  	// Handle both *ed25519.PrivateKey and ed25519.PrivateKey types
   362  	var ed25519PrivateKey ed25519.PrivateKey
   363  	switch key := rawKey.(type) {
   364  	case ed25519.PrivateKey:
   365  		ed25519PrivateKey = key
   366  	case *ed25519.PrivateKey:
   367  		ed25519PrivateKey = *key
   368  	default:
   369  		return nil, fmt.Errorf("SSH private key is not an Ed25519 key, got %T", rawKey)
   370  	}
   371  
   372  	publicKey := ed25519PrivateKey.Public().(ed25519.PublicKey)
   373  
   374  	return &Ed25519KeyPair{
   375  		PrivateKey: ed25519PrivateKey,
   376  		PublicKey:  publicKey,
   377  	}, nil
   378  }