github.com/jasoet/gopki@v1.15.0/internal/crypto/curve25519.go (about) 1 // Package crypto provides complex cryptographic algorithms used internally by GoPKI. 2 // 3 // This package contains mathematical operations that are not available in Go's 4 // standard library or third-party dependencies. These implementations follow 5 // established RFCs and cryptographic standards. 6 // 7 // SECURITY NOTE: These implementations are for educational and compatibility 8 // purposes. For production use, prefer well-tested library implementations 9 // when available. 10 package crypto 11 12 import ( 13 "crypto/ed25519" 14 "fmt" 15 ) 16 17 // Ed25519ToX25519PublicKey converts an Ed25519 public key to X25519 public key 18 // following RFC 7748 Section 4.1 ("Curve25519"). 19 // 20 // This conversion is necessary for envelope encryption where we have only an 21 // Ed25519 public key but need to perform X25519 ECDH key agreement. 22 // 23 // Mathematical Background: 24 // - Ed25519 uses Edwards25519 curve: -x² + y² = 1 + d*x²*y² 25 // - X25519 uses Montgomery curve Curve25519: B*v² = u³ + A*u² + u 26 // - Both curves are birationally equivalent over the same prime field 27 // - The conversion formula from Edwards (x,y) to Montgomery (u,v) is: 28 // u = (1 + y) / (1 - y) mod p 29 // v = sqrt(-486664) * u / x mod p (we only need u-coordinate for ECDH) 30 // 31 // RFC References: 32 // - RFC 7748: "Elliptic Curves for Security" 33 // - RFC 8032: "Edwards-Curve Digital Signature Algorithm (EdDSA)" 34 // 35 // Parameters: 36 // - ed25519PublicKey: 32-byte Ed25519 public key 37 // 38 // Returns: 39 // - []byte: 32-byte X25519 public key (u-coordinate only) 40 // - error: Conversion error or invalid input 41 // 42 // Example: 43 // 44 // ed25519PubKey := []byte{...} // 32 bytes 45 // x25519PubKey, err := Ed25519ToX25519PublicKey(ed25519PubKey) 46 // if err != nil { 47 // log.Fatal("Conversion failed:", err) 48 // } 49 // // Use x25519PubKey for ECDH operations 50 func Ed25519ToX25519PublicKey(ed25519PublicKey ed25519.PublicKey) ([]byte, error) { 51 if len(ed25519PublicKey) != 32 { 52 return nil, fmt.Errorf("invalid Ed25519 public key length: expected 32 bytes, got %d", len(ed25519PublicKey)) 53 } 54 55 // The Ed25519 public key is the y-coordinate on Edwards25519 56 y := make([]byte, 32) 57 copy(y, ed25519PublicKey) 58 59 // Convert from little-endian to big-endian for arithmetic operations 60 // (Go's crypto libraries use little-endian, but we need big-endian for field arithmetic) 61 reverseBytes(y) 62 63 // Convert Edwards y-coordinate to Montgomery u-coordinate 64 // Formula: u = (1 + y) / (1 - y) mod p 65 // where p = 2^255 - 19 (the prime field for Curve25519) 66 u, err := edwardsToMontgomery(y) 67 if err != nil { 68 return nil, fmt.Errorf("Edwards to Montgomery conversion failed: %w", err) 69 } 70 71 // Convert back to little-endian for X25519 format 72 reverseBytes(u) 73 74 return u, nil 75 } 76 77 // edwardsToMontgomery converts Edwards y-coordinate to Montgomery u-coordinate 78 // using the formula: u = (1 + y) / (1 - y) mod p 79 func edwardsToMontgomery(y []byte) ([]byte, error) { 80 // Curve25519 prime: p = 2^255 - 19 81 p := []byte{ 82 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 83 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 84 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 85 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xed, 86 } 87 88 // Check if y >= p (invalid point) 89 if compareBytes(y, p) >= 0 { 90 return nil, fmt.Errorf("invalid Edwards coordinate: y >= p") 91 } 92 93 // Create properly sized 1 for arithmetic 94 one := make([]byte, 32) 95 one[31] = 1 96 97 // Calculate 1 + y mod p 98 oneY := addMod(one, y, p) 99 100 // Calculate 1 - y mod p 101 oneMinusY := subMod(one, y, p) 102 103 // Check for degenerate case: 1 - y = 0 (point at infinity) 104 if isZero(oneMinusY) { 105 return nil, fmt.Errorf("conversion failed: point at infinity") 106 } 107 108 // Calculate u = (1 + y) / (1 - y) mod p 109 // This is equivalent to (1 + y) * (1 - y)^(-1) mod p 110 invOneMinusY, err := modInverse(oneMinusY, p) 111 if err != nil { 112 return nil, fmt.Errorf("modular inverse failed: %w", err) 113 } 114 115 u := mulMod(oneY, invOneMinusY, p) 116 return u, nil 117 } 118 119 // reverseBytes reverses a byte slice in place (little-endian <-> big-endian) 120 func reverseBytes(b []byte) { 121 for i := 0; i < len(b)/2; i++ { 122 b[i], b[len(b)-1-i] = b[len(b)-1-i], b[i] 123 } 124 } 125 126 // compareBytes compares two byte slices as big-endian integers 127 // Returns: -1 if a < b, 0 if a == b, 1 if a > b 128 func compareBytes(a, b []byte) int { 129 // Handle case where leading zeros make values equal 130 // Remove leading zeros for accurate comparison 131 aTrimmed := trimLeadingZeros(a) 132 bTrimmed := trimLeadingZeros(b) 133 134 // Compare lengths first 135 if len(aTrimmed) < len(bTrimmed) { 136 return -1 137 } 138 if len(aTrimmed) > len(bTrimmed) { 139 return 1 140 } 141 142 // Compare byte by byte 143 for i := 0; i < len(aTrimmed); i++ { 144 if aTrimmed[i] < bTrimmed[i] { 145 return -1 146 } 147 if aTrimmed[i] > bTrimmed[i] { 148 return 1 149 } 150 } 151 return 0 152 } 153 154 // trimLeadingZeros removes leading zero bytes 155 func trimLeadingZeros(b []byte) []byte { 156 i := 0 157 for i < len(b) && b[i] == 0 { 158 i++ 159 } 160 if i == len(b) { 161 return []byte{0} // Return single zero for all-zero input 162 } 163 return b[i:] 164 } 165 166 // addMod computes (a + b) mod m 167 func addMod(a, b, m []byte) []byte { 168 // Simple implementation - for production, use optimized big integer library 169 // This is a educational implementation following RFC 7748 170 171 // Convert to Go's big.Int for arithmetic (this is the complex part we're isolating) 172 return performBigIntOperation(a, b, m, "add") 173 } 174 175 // subMod computes (a - b) mod m 176 func subMod(a, b, m []byte) []byte { 177 return performBigIntOperation(a, b, m, "sub") 178 } 179 180 // mulMod computes (a * b) mod m 181 func mulMod(a, b, m []byte) []byte { 182 return performBigIntOperation(a, b, m, "mul") 183 } 184 185 // modInverse computes a^(-1) mod m using extended Euclidean algorithm 186 func modInverse(a, m []byte) ([]byte, error) { 187 result := performBigIntOperation(a, nil, m, "inv") 188 if result == nil { 189 return nil, fmt.Errorf("modular inverse does not exist") 190 } 191 return result, nil 192 } 193 194 // isZero checks if a byte slice represents zero 195 func isZero(a []byte) bool { 196 for _, b := range a { 197 if b != 0 { 198 return false 199 } 200 } 201 return true 202 }