func (b Base58) Base582Big() *big.Int { answer := new(big.Int) for i := 0; i < len(b); i++ { answer.Mul(answer, big.NewInt(58)) //multiply current value by 58 answer.Add(answer, big.NewInt(int64(revalp[string(b[i:i+1])]))) //add value of the current letter } return answer }
// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and // returns its double, also in Jacobian form. func (curve *Curve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b delta := new(big.Int).Mul(z, z) delta.Mod(delta, curve.P) gamma := new(big.Int).Mul(y, y) gamma.Mod(gamma, curve.P) alpha := new(big.Int).Sub(x, delta) if alpha.Sign() == -1 { alpha.Add(alpha, curve.P) } alpha2 := new(big.Int).Add(x, delta) alpha.Mul(alpha, alpha2) alpha2.Set(alpha) alpha.Lsh(alpha, 1) alpha.Add(alpha, alpha2) beta := alpha2.Mul(x, gamma) x3 := new(big.Int).Mul(alpha, alpha) beta8 := new(big.Int).Lsh(beta, 3) x3.Sub(x3, beta8) for x3.Sign() == -1 { x3.Add(x3, curve.P) } x3.Mod(x3, curve.P) z3 := new(big.Int).Add(y, z) z3.Mul(z3, z3) z3.Sub(z3, gamma) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Sub(z3, delta) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Mod(z3, curve.P) beta.Lsh(beta, 2) beta.Sub(beta, x3) if beta.Sign() == -1 { beta.Add(beta, curve.P) } y3 := alpha.Mul(alpha, beta) gamma.Mul(gamma, gamma) gamma.Lsh(gamma, 3) gamma.Mod(gamma, curve.P) y3.Sub(y3, gamma) if y3.Sign() == -1 { y3.Add(y3, curve.P) } y3.Mod(y3, curve.P) return x3, y3, z3 }
// IsOnBitCurve returns true if the given (x,y) lies on the BitCurve. func (BitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { // y² = x³ + b y2 := new(big.Int).Mul(y, y) //y² y2.Mod(y2, BitCurve.P) //y²%P x3 := new(big.Int).Mul(x, x) //x² x3.Mul(x3, x) //x³ x3.Add(x3, BitCurve.B) //x³+B x3.Mod(x3, BitCurve.P) //(x³+B)%P return x3.Cmp(y2) == 0 }
/** * Store the solution in the Calculator output lines. */ func (calc *Calculator) setSolutionLine() { var solution big.Int if calc.operator == '+' { solution.Add(&calc.operands[0], &calc.operands[1]) } else if calc.operator == '-' { solution.Sub(&calc.operands[0], &calc.operands[1]) } else { solution.Mul(&calc.operands[0], &calc.operands[1]) } calc.lines[len(calc.lines)-1] = solution.String() }
// modInverse returns ia, the inverse of a in the multiplicative group of prime // order n. It requires that a be a member of the group (i.e. less than n). func modInverse(a, n *big.Int) (ia *big.Int) { g := new(big.Int) x := new(big.Int) y := new(big.Int) big.GcdInt(g, x, y, a, n) if big.CmpInt(x, bigOne) < 0 { // 0 is not the multiplicative inverse of any element so, if x // < 1, then x is negative. x.Add(x, n) } return x }
// parseBigInt treats the given bytes as a big-endian, signed integer and returns // the result. func parseBigInt(bytes []byte) *big.Int { ret := new(big.Int) if len(bytes) > 0 && bytes[0]&0x80 == 0x80 { // This is a negative number. notBytes := make([]byte, len(bytes)) for i := range notBytes { notBytes[i] = ^bytes[i] } ret.SetBytes(notBytes) ret.Add(ret, bigOne) ret.Neg(ret) return ret } ret.SetBytes(bytes) return ret }
// IsOnCurve returns true if the given (x,y) lies on the curve. func (curve *Curve) IsOnCurve(x, y *big.Int) bool { // y² = x³ - 3x + b y2 := new(big.Int).Mul(y, y) y2.Mod(y2, curve.P) x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) threeX := new(big.Int).Lsh(x, 1) threeX.Add(threeX, x) x3.Sub(x3, threeX) x3.Add(x3, curve.B) x3.Mod(x3, curve.P) return x3.Cmp(y2) == 0 }
func (curve *Curve) double(p *Point) *Point { fmt.Printf("d") lambda_numerator := new(big.Int) lambda_denominator := new(big.Int) lambda := new(big.Int) lambda_numerator.Exp(p.X, BigTwo, curve.P) lambda_numerator.Mul(lambda_numerator, BigThree) lambda_numerator.Add(lambda_numerator, curve.A) lambda_denominator.Mul(BigTwo, p.Y) lambda_denominator, ok := modInverse(lambda_denominator, curve.P) if !ok { fmt.Printf("Its not OKAY\n") return nil } lambda.Mul(lambda_numerator, lambda_denominator) lambda = lambda.Mod(lambda, curve.P) p3 := NewPoint() temp := new(big.Int) temp2 := new(big.Int) //temp3 := new(big.Int) //temp4 := new(big.Int) //temp5 := new(big.Int) //temp6 := new(big.Int) p3.X.Sub(temp.Exp(lambda, BigTwo, curve.P), temp2.Mul(BigTwo, p.X)) p3.X = p3.X.Mod(p3.X, curve.P) p3.Y.Sub(p.X, p3.X) p3.Y.Mul(p3.Y, lambda) p3.Y = p3.Y.Sub(p3.Y, p.Y) p3.Y = p3.Y.Mod(p3.Y, curve.P) if p3.X.Cmp(BigZero) == -1 { //if X is negative p3.X.Neg(p3.X) p3.X.Sub(curve.P, p3.X) } if p3.Y.Cmp(BigZero) == -1 { //if Y is negative p3.Y.Neg(p3.Y) p3.Y.Sub(curve.P, p3.Y) } return p3 }
// modInverse returns ia, the inverse of a in the multiplicative group of prime // order n. It requires that a be a member of the group (i.e. less than n). func modInverse(a, n *big.Int) (ia *big.Int, ok bool) { g := new(big.Int) x := new(big.Int) y := new(big.Int) big.GcdInt(g, x, y, a, n) if g.Cmp(bigOne) != 0 { // In this case, a and n aren't coprime and we cannot calculate // the inverse. This happens because the values of n are nearly // prime (being the product of two primes) rather than truly // prime. return } if x.Cmp(bigOne) < 0 { // 0 is not the multiplicative inverse of any element so, if x // < 1, then x is negative. x.Add(x, n) } return x, true }
func binaryIntOp(x *big.Int, op token.Token, y *big.Int) interface{} { var z big.Int switch op { case token.ADD: return z.Add(x, y) case token.SUB: return z.Sub(x, y) case token.MUL: return z.Mul(x, y) case token.QUO: return z.Quo(x, y) case token.REM: return z.Rem(x, y) case token.AND: return z.And(x, y) case token.OR: return z.Or(x, y) case token.XOR: return z.Xor(x, y) case token.AND_NOT: return z.AndNot(x, y) case token.SHL: panic("unimplemented") case token.SHR: panic("unimplemented") case token.EQL: return x.Cmp(y) == 0 case token.NEQ: return x.Cmp(y) != 0 case token.LSS: return x.Cmp(y) < 0 case token.LEQ: return x.Cmp(y) <= 0 case token.GTR: return x.Cmp(y) > 0 case token.GEQ: return x.Cmp(y) >= 0 } panic("unreachable") }
func number_add(x, y Obj) Obj { xfx := (uintptr(unsafe.Pointer(x)) & fixnum_mask) == fixnum_tag yfx := (uintptr(unsafe.Pointer(y)) & fixnum_mask) == fixnum_tag if xfx && yfx { i1 := uintptr(unsafe.Pointer(x)) i2 := uintptr(unsafe.Pointer(y)) r := (int(i1) >> fixnum_shift) + (int(i2) >> fixnum_shift) if r > fixnum_min && r < fixnum_max { return Make_fixnum(r) } else { return wrap(big.NewInt(int64(r))) } } if (!xfx && (uintptr(unsafe.Pointer(x))&heap_mask) != heap_tag) || (!yfx && (uintptr(unsafe.Pointer(y))&heap_mask) != heap_tag) { panic("bad type") } if xfx { return number_add(y, x) } switch vx := (*x).(type) { case *big.Int: var z *big.Int = big.NewInt(0) if yfx { vy := big.NewInt(int64(fixnum_to_int(y))) return wrap(z.Add(vx, vy)) } switch vy := (*y).(type) { case *big.Int: return simpBig(z.Add(vx, vy)) default: panic("bad type") } } panic("bad type") }
// GenerateParameters puts a random, valid set of DSA parameters into params. // This function takes many seconds, even on fast machines. func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err os.Error) { // This function doesn't follow FIPS 186-3 exactly in that it doesn't // use a verification seed to generate the primes. The verification // seed doesn't appear to be exported or used by other code and // omitting it makes the code cleaner. var L, N int switch sizes { case L1024N160: L = 1024 N = 160 case L2048N224: L = 2048 N = 224 case L2048N256: L = 2048 N = 256 case L3072N256: L = 3072 N = 256 default: return os.ErrorString("crypto/dsa: invalid ParameterSizes") } qBytes := make([]byte, N/8) pBytes := make([]byte, L/8) q := new(big.Int) p := new(big.Int) rem := new(big.Int) one := new(big.Int) one.SetInt64(1) GeneratePrimes: for { _, err = io.ReadFull(rand, qBytes) if err != nil { return } qBytes[len(qBytes)-1] |= 1 qBytes[0] |= 0x80 q.SetBytes(qBytes) if !big.ProbablyPrime(q, numMRTests) { continue } for i := 0; i < 4*L; i++ { _, err = io.ReadFull(rand, pBytes) if err != nil { return } pBytes[len(pBytes)-1] |= 1 pBytes[0] |= 0x80 p.SetBytes(pBytes) rem.Mod(p, q) rem.Sub(rem, one) p.Sub(p, rem) if p.BitLen() < L { continue } if !big.ProbablyPrime(p, numMRTests) { continue } params.P = p params.Q = q break GeneratePrimes } } h := new(big.Int) h.SetInt64(2) g := new(big.Int) pm1 := new(big.Int).Sub(p, one) e := new(big.Int).Div(pm1, q) for { g.Exp(h, e, p) if g.Cmp(one) == 0 { h.Add(h, one) continue } params.G = g return } panic("unreachable") }
// decrypt performs an RSA decryption, resulting in a plaintext integer. If a // random source is given, RSA blinding is used. func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.Error) { // TODO(agl): can we get away with reusing blinds? if c.Cmp(priv.N) > 0 { err = DecryptionError{} return } var ir *big.Int if random != nil { // Blinding enabled. Blinding involves multiplying c by r^e. // Then the decryption operation performs (m^e * r^e)^d mod n // which equals mr mod n. The factor of r can then be removed // by multiplying by the multiplicative inverse of r. var r *big.Int for { r, err = rand.Int(random, priv.N) if err != nil { return } if r.Cmp(bigZero) == 0 { r = bigOne } var ok bool ir, ok = modInverse(r, priv.N) if ok { break } } bigE := big.NewInt(int64(priv.E)) rpowe := new(big.Int).Exp(r, bigE, priv.N) cCopy := new(big.Int).Set(c) cCopy.Mul(cCopy, rpowe) cCopy.Mod(cCopy, priv.N) c = cCopy } if priv.Precomputed.Dp == nil { m = new(big.Int).Exp(c, priv.D, priv.N) } else { // We have the precalculated values needed for the CRT. m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0]) m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1]) m.Sub(m, m2) if m.Sign() < 0 { m.Add(m, priv.Primes[0]) } m.Mul(m, priv.Precomputed.Qinv) m.Mod(m, priv.Primes[0]) m.Mul(m, priv.Primes[1]) m.Add(m, m2) for i, values := range priv.Precomputed.CRTValues { prime := priv.Primes[2+i] m2.Exp(c, values.Exp, prime) m2.Sub(m2, m) m2.Mul(m2, values.Coeff) m2.Mod(m2, prime) if m2.Sign() < 0 { m2.Add(m2, prime) } m2.Mul(m2, values.R) m.Add(m, m2) } } if ir != nil { // Unblind. m.Mul(m, ir) m.Mod(m, priv.N) } return }
func main() { flag.Parse() // parsovani parametru prikazove radky rand.Seed(time.Nanoseconds()) // inicializace generatoru nahodnych cisel if *generateKeys { SaveKeys(GenerateKeys(*keyLength)) } // rozdeleni souboru na vice mensich podle delky klice if *splitFile != "" { rights := 0600 n, _ := ReadPublicKey() bytes := readFile(*splitFile) nl := len(n.Bytes()) - 1 i := 0 for ; i < len(bytes)/nl; i++ { writeToFile(partfile(i), bytes[i*nl:(i+1)*nl], rights) } if len(bytes[i*nl:]) > 0 { // pokud deleni nevychazi presne writeToFile(partfile(i), bytes[i*nl:], rights) i++ } // informacni soubor writeToFile(*prefix+".info", strings.Bytes(fmt.Sprintf("%d", i)), rights) } // zasifruje/rozsifruje vsechny soubory verejnym klicem if *encrypFiles { n, e := ReadPublicKey() max := msgscount() for i := 0; i < max; i++ { file := readFile(partfile(i)) bs := crypt(e, n, file) writeToFile(partfile(i), bs, 0600) } } // rozsifruje/zasifruje vsechny soubory soukromym klicem if *decrypFiles { p, q, d := ReadPrivateKey() pinv := new(big.Int).Mul(p, invMod(p, q)) // = p*(p^-1 mod q) qinv := new(big.Int).Mul(q, invMod(q, p)) // = q*(q^-1 mod p) n := new(big.Int).Mul(p, q) max := msgscount() for i := 0; i < max; i++ { file := readFile(partfile(i)) // CINSKA VETA O ZBYTCICH bp := new(big.Int).SetBytes(crypt(d, p, file)) // decrypt mod p bq := new(big.Int).SetBytes(crypt(d, q, file)) // decrypt mod q // bs = bp * qinv + bq * binv (mod n) bs := new(big.Int).Mul(bp, qinv) bs.Add(bs, new(big.Int).Mul(bq, pinv)) bs.Mod(bs, n) writeToFile(partfile(i), bs.Bytes(), 0600) } } // spojeni souboru do jednoho if *joinFile != "" { max := msgscount() var bs []byte for i := 0; i < max; i++ { file := readFile(partfile(i)) bs = bytes.Add(bs, file) } writeToFile(*joinFile, bs, 0600) } }
// decrypt performs an RSA decryption, resulting in a plaintext integer. If a // random source is given, RSA blinding is used. func decrypt(rand io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.Error) { // TODO(agl): can we get away with reusing blinds? if c.Cmp(priv.N) > 0 { err = DecryptionError{} return } var ir *big.Int if rand != nil { // Blinding enabled. Blinding involves multiplying c by r^e. // Then the decryption operation performs (m^e * r^e)^d mod n // which equals mr mod n. The factor of r can then be removed // by multipling by the multiplicative inverse of r. var r *big.Int for { r, err = randomNumber(rand, priv.N) if err != nil { return } if r.Cmp(bigZero) == 0 { r = bigOne } var ok bool ir, ok = modInverse(r, priv.N) if ok { break } } bigE := big.NewInt(int64(priv.E)) rpowe := new(big.Int).Exp(r, bigE, priv.N) c.Mul(c, rpowe) c.Mod(c, priv.N) } priv.rwMutex.RLock() if priv.dP == nil && priv.P != nil { priv.rwMutex.RUnlock() priv.rwMutex.Lock() if priv.dP == nil && priv.P != nil { priv.precompute() } priv.rwMutex.Unlock() priv.rwMutex.RLock() } if priv.dP == nil { m = new(big.Int).Exp(c, priv.D, priv.N) } else { // We have the precalculated values needed for the CRT. m = new(big.Int).Exp(c, priv.dP, priv.P) m2 := new(big.Int).Exp(c, priv.dQ, priv.Q) m.Sub(m, m2) if m.Sign() < 0 { m.Add(m, priv.P) } m.Mul(m, priv.qInv) m.Mod(m, priv.P) m.Mul(m, priv.Q) m.Add(m, m2) if priv.dR != nil { // 3-prime CRT. m2.Exp(c, priv.dR, priv.R) m2.Sub(m2, m) m2.Mul(m2, priv.tr) m2.Mod(m2, priv.R) if m2.Sign() < 0 { m2.Add(m2, priv.R) } m2.Mul(m2, priv.pq) m.Add(m, m2) } } priv.rwMutex.RUnlock() if ir != nil { // Unblind. m.Mul(m, ir) m.Mod(m, priv.N) } return }
// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and // (x2, y2, z2) and returns their sum, also in Jacobian form. func (curve *Curve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl z1z1 := new(big.Int).Mul(z1, z1) z1z1.Mod(z1z1, curve.P) z2z2 := new(big.Int).Mul(z2, z2) z2z2.Mod(z2z2, curve.P) u1 := new(big.Int).Mul(x1, z2z2) u1.Mod(u1, curve.P) u2 := new(big.Int).Mul(x2, z1z1) u2.Mod(u2, curve.P) h := new(big.Int).Sub(u2, u1) if h.Sign() == -1 { h.Add(h, curve.P) } i := new(big.Int).Lsh(h, 1) i.Mul(i, i) j := new(big.Int).Mul(h, i) s1 := new(big.Int).Mul(y1, z2) s1.Mul(s1, z2z2) s1.Mod(s1, curve.P) s2 := new(big.Int).Mul(y2, z1) s2.Mul(s2, z1z1) s2.Mod(s2, curve.P) r := new(big.Int).Sub(s2, s1) if r.Sign() == -1 { r.Add(r, curve.P) } r.Lsh(r, 1) v := new(big.Int).Mul(u1, i) x3 := new(big.Int).Set(r) x3.Mul(x3, x3) x3.Sub(x3, j) x3.Sub(x3, v) x3.Sub(x3, v) x3.Mod(x3, curve.P) y3 := new(big.Int).Set(r) v.Sub(v, x3) y3.Mul(y3, v) s1.Mul(s1, j) s1.Lsh(s1, 1) y3.Sub(y3, s1) y3.Mod(y3, curve.P) z3 := new(big.Int).Add(z1, z2) z3.Mul(z3, z3) z3.Sub(z3, z1z1) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Sub(z3, z2z2) if z3.Sign() == -1 { z3.Add(z3, curve.P) } z3.Mul(z3, h) z3.Mod(z3, curve.P) return x3, y3, z3 }
func main() { // integer is := "1234" fmt.Println("original: ", is) i, err := strconv.Atoi(is) if err != nil { fmt.Println(err) return } // assignment back to original variable shows result is the same type. is = strconv.Itoa(i + 1) fmt.Println("incremented:", is) // error checking worthwhile fmt.Println() _, err = strconv.Atoi(" 1234") // whitespace not allowed fmt.Println(err) _, err = strconv.Atoi("12345678901") fmt.Println(err) _, err = strconv.Atoi("_1234") fmt.Println(err) _, err = strconv.Atof64("12.D34") fmt.Println(err) // float fmt.Println() fs := "12.34" fmt.Println("original: ", fs) f, err := strconv.Atof64(fs) if err != nil { fmt.Println(err) return } // various options on Ftoa64 produce different formats. All are valid // input to Atof64, so result format does not have to match original // format. (Matching original format would take a lot of code.) fs = strconv.Ftoa64(f+1, 'g', -1) fmt.Println("incremented:", fs) fs = strconv.Ftoa64(f+1, 'e', 4) fmt.Println("what format?", fs) // complex // strconv package doesn't handle complex types, but fmt does. // (fmt can be used on ints and floats too, but strconv is more efficient.) fmt.Println() cs := "(12+34i)" fmt.Println("original: ", cs) var c complex128 _, err = fmt.Sscan(cs, &c) if err != nil { fmt.Println(err) return } cs = fmt.Sprint(c + 1) fmt.Println("incremented:", cs) // big integers have their own functions fmt.Println() bs := "170141183460469231731687303715884105728" fmt.Println("original: ", bs) var b, one big.Int _, ok := b.SetString(bs, 10) if !ok { fmt.Println("big.SetString fail") return } one.SetInt64(1) bs = b.Add(&b, &one).String() fmt.Println("incremented:", bs) }