github.com/jasoet/gopki@v1.15.0/internal/crypto/bigint_ops.go (about) 1 // Package crypto - Big Integer Operations 2 // 3 // This file contains the complex mathematical operations using Go's big.Int 4 // library for arbitrary precision arithmetic required for elliptic curve 5 // point conversion between Ed25519 and X25519. 6 // 7 // These operations implement field arithmetic over the prime field p = 2^255 - 19 8 // used by Curve25519, as specified in RFC 7748. 9 10 package crypto 11 12 import ( 13 "math/big" 14 ) 15 16 // performBigIntOperation performs various big integer operations 17 // This centralizes all the complex mathematical operations in one place 18 func performBigIntOperation(a, b, m []byte, operation string) []byte { 19 // Convert byte arrays to big.Int 20 aBig := new(big.Int).SetBytes(a) 21 mBig := new(big.Int).SetBytes(m) 22 23 var result *big.Int 24 25 switch operation { 26 case "add": 27 bBig := new(big.Int).SetBytes(b) 28 result = new(big.Int).Add(aBig, bBig) 29 result.Mod(result, mBig) 30 31 case "sub": 32 bBig := new(big.Int).SetBytes(b) 33 result = new(big.Int).Sub(aBig, bBig) 34 // Handle negative results: if result < 0, add modulus 35 if result.Sign() < 0 { 36 result.Add(result, mBig) 37 } 38 result.Mod(result, mBig) 39 40 case "mul": 41 bBig := new(big.Int).SetBytes(b) 42 result = new(big.Int).Mul(aBig, bBig) 43 result.Mod(result, mBig) 44 45 case "inv": 46 // Modular inverse using extended Euclidean algorithm 47 result = new(big.Int).ModInverse(aBig, mBig) 48 if result == nil { 49 return nil // Inverse doesn't exist 50 } 51 52 default: 53 return nil 54 } 55 56 // Convert back to 32-byte array 57 resultBytes := result.Bytes() 58 59 // Pad to 32 bytes (big-endian) 60 padded := make([]byte, 32) 61 copy(padded[32-len(resultBytes):], resultBytes) 62 63 return padded 64 }