certichain

Blockchain built from scratch for verifying document's legitimacy.
Log | Files | Refs | README | LICENSE

keys.go (4093B)


      1 // Copyright 2026 Shivakumar (Certichain)
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package crypto
     16 
     17 import (
     18 	"crypto/ed25519"
     19 	"crypto/rand"
     20 	"crypto/x509"
     21 	"encoding/pem"
     22 	"errors"
     23 	"fmt"
     24 )
     25 
     26 // GenerateKeyPair generates a new Ed25519 keypair (public, private)
     27 // using cryptographically secure random source.
     28 func GenerateKeyPair() (ed25519.PublicKey, ed25519.PrivateKey, error) {
     29 	return ed25519.GenerateKey(rand.Reader)
     30 }
     31 
     32 // PrivateKeyToPEM serializes a Ed25519 private key into PEM-encoded
     33 // PKCS#8 format.
     34 //
     35 // Output format:
     36 //
     37 //	-----BEGIN PRIVATE KEY-----
     38 //	(base64 PKCS#8 DER bytes)
     39 //	-----END PRIVATE KEY-----
     40 func PrivateKeyToPEM(key ed25519.PrivateKey) ([]byte, error) {
     41 	if len(key) != ed25519.PrivateKeySize {
     42 		return nil, errors.New("invalid Ed25519 private key size")
     43 	}
     44 
     45 	der, err := x509.MarshalPKCS8PrivateKey(key)
     46 	if err != nil {
     47 		return nil, fmt.Errorf("marshalling private key: %w", err)
     48 	}
     49 
     50 	block := &pem.Block{
     51 		Type:  "PRIVATE KEY",
     52 		Bytes: der,
     53 	}
     54 
     55 	return pem.EncodeToMemory(block), nil
     56 }
     57 
     58 // PublicKeyToPEM serializes a Ed25519 public key into PEM-encoded
     59 // PKIX format.
     60 //
     61 // Output format:
     62 //
     63 //	-----BEGIN PUBLIC KEY-----
     64 //	(base64 PKIX DER bytes)
     65 //	-----END PUBLIC KEY-----
     66 func PublicKeyToPEM(key ed25519.PublicKey) ([]byte, error) {
     67 	if len(key) != ed25519.PublicKeySize {
     68 		return nil, errors.New("invalid Ed25519 public key size")
     69 	}
     70 
     71 	der, err := x509.MarshalPKIXPublicKey(key)
     72 	if err != nil {
     73 		return nil, fmt.Errorf("marshalling public key: %w", err)
     74 	}
     75 
     76 	block := &pem.Block{
     77 		Type:  "PUBLIC KEY",
     78 		Bytes: der,
     79 	}
     80 
     81 	return pem.EncodeToMemory(block), nil
     82 }
     83 
     84 // PrivateKeyFromPEM parses a PEM-encoded PKCS#8 Ed25519 private key
     85 // and validates its structure and size.
     86 //
     87 // Expected PEM type:
     88 //
     89 //	PRIVATE KEY
     90 func PrivateKeyFromPEM(pemBytes []byte) (ed25519.PrivateKey, error) {
     91 	block, rest := pem.Decode(pemBytes)
     92 	if block == nil {
     93 		return nil, errors.New("invalid PEM data")
     94 	}
     95 
     96 	if len(rest) != 0 {
     97 		return nil, errors.New("extra trailing data after PEM block")
     98 	}
     99 
    100 	if block.Type != "PRIVATE KEY" {
    101 		return nil, errors.New("PEM does not contain a private key")
    102 	}
    103 
    104 	key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
    105 	if err != nil {
    106 		return nil, fmt.Errorf("parsing private key: %w", err)
    107 	}
    108 
    109 	privateKey, ok := key.(ed25519.PrivateKey)
    110 	if !ok {
    111 		return nil, errors.New("not an Ed25519 key type")
    112 	}
    113 
    114 	if len(privateKey) != ed25519.PrivateKeySize {
    115 		return nil, errors.New("invalid private key")
    116 	}
    117 
    118 	return privateKey, nil
    119 }
    120 
    121 // PublicKeyFromPEM parses a PEM-encoded PKIX Ed25519 public key
    122 // and validates its structure and size.
    123 //
    124 // Expected PEM type:
    125 //
    126 //	PUBLIC KEY
    127 func PublicKeyFromPEM(pemBytes []byte) (ed25519.PublicKey, error) {
    128 	block, rest := pem.Decode(pemBytes)
    129 	if block == nil {
    130 		return nil, errors.New("invalid PEM data")
    131 	}
    132 
    133 	if len(rest) != 0 {
    134 		return nil, errors.New("extra trailing data after pem block")
    135 	}
    136 
    137 	if block.Type != "PUBLIC KEY" {
    138 		return nil, errors.New("PEM does not contain public key")
    139 	}
    140 
    141 	key, err := x509.ParsePKIXPublicKey(block.Bytes)
    142 	if err != nil {
    143 		return nil, fmt.Errorf("parsing public key: %w", err)
    144 	}
    145 
    146 	publicKey, ok := key.(ed25519.PublicKey)
    147 	if !ok {
    148 		return nil, errors.New("not an Ed25519 public key type")
    149 	}
    150 
    151 	if len(publicKey) != ed25519.PublicKeySize {
    152 		return nil, errors.New("invalid Ed25519 public key size")
    153 	}
    154 
    155 	return publicKey, nil
    156 }
    157 
    158 // PublicKeyFromPrivate derives the Ed25519 public key from the private key
    159 func PublicKeyFromPrivate(key ed25519.PrivateKey) ed25519.PublicKey {
    160 	return key.Public().(ed25519.PublicKey)
    161 }