move to lib

This commit is contained in:
filifa
2025-09-29 21:52:52 -04:00
parent d2275cd69f
commit b55fe61820
16 changed files with 452 additions and 296 deletions

View File

@@ -17,11 +17,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"errors"
"fmt"
"math/big"
"github.com/spf13/cobra"
"scm.dairydemon.net/filifa/mathtools/internal/lib"
)
var discreteLogModulus string
@@ -29,62 +29,6 @@ var discreteLogBase string
var discreteLogElement string
var discreteLogOrder string
// whyyyy doesn't math/big have a ceil functionnnn
func ceilSqrt(x *big.Int) *big.Int {
z := new(big.Int).Sqrt(x)
s := new(big.Int).Exp(z, big.NewInt(2), nil)
if s.Cmp(x) != 0 {
z.Add(z, big.NewInt(1))
}
return z
}
// TODO: this can be extended to work with n, b not coprime
// https://cp-algorithms.com/algebra/discrete-log.html
func babyStepGiantStep(n, b, x, order *big.Int) (*big.Int, error) {
z := new(big.Int).GCD(nil, nil, b, n)
if z.Cmp(big.NewInt(1)) != 0 {
return nil, fmt.Errorf("base %v and modulus %v are not coprime", b, n)
}
var m *big.Int
if order == nil {
// m = ceil(sqrt(n - 1))
z := big.NewInt(1)
z.Sub(n, z)
m = ceilSqrt(z)
} else {
m = ceilSqrt(order)
}
table := make(map[string]*big.Int)
for j := big.NewInt(1); j.Cmp(m) <= 0; j.Add(j, big.NewInt(1)) {
a := new(big.Int).Exp(b, j, n)
table[a.String()] = new(big.Int).Set(j)
}
// p = b^-m modulo n
p := new(big.Int).Neg(m)
p.Exp(b, p, n)
gamma := new(big.Int).Set(x)
for i := big.NewInt(0); i.Cmp(m) == -1; i.Add(i, big.NewInt(1)) {
j, ok := table[gamma.String()]
if ok {
i.Mul(i, m)
i.Add(i, j)
return i, nil
}
gamma.Mul(gamma, p)
gamma.Mod(gamma, n)
}
return nil, errors.New("no solution")
}
func discreteLog(cmd *cobra.Command, args []string) {
m, ok := new(big.Int).SetString(discreteLogModulus, 10)
if !ok {
@@ -109,7 +53,7 @@ func discreteLog(cmd *cobra.Command, args []string) {
}
}
k, err := babyStepGiantStep(m, b, x, order)
k, err := lib.BabyStepGiantStep(m, b, x, order)
if err != nil {
cobra.CheckErr(err)
}