// Compile instruction // // Attempts to compile and parse the given instruction in "s" // and returns the byte sequence func CompileInstr(s interface{}) ([]byte, error) { switch s.(type) { case string: str := s.(string) isOp := IsOpCode(str) if isOp { return []byte{OpCodes[str]}, nil } // Check for pre formatted byte array // Jumps are preformatted if []byte(str)[0] == 0 { return []byte(str), nil } num := new(big.Int) _, success := num.SetString(str, 0) // Assume regular bytes during compilation if !success { num.SetBytes([]byte(str)) } return num.Bytes(), nil case int: //num := bigToBytes(big.NewInt(int64(s.(int))), 256) return big.NewInt(int64(s.(int))).Bytes(), nil case []byte: return new(big.Int).SetBytes(s.([]byte)).Bytes(), nil } return nil, nil }
func TestDecryptOAEP(t *testing.T) { random := rand.Reader sha1 := sha1.New() n := new(big.Int) d := new(big.Int) for i, test := range testEncryptOAEPData { n.SetString(test.modulus, 16) d.SetString(test.d, 16) private := new(PrivateKey) private.PublicKey = PublicKey{n, test.e} private.D = d for j, message := range test.msgs { out, err := DecryptOAEP(sha1, nil, private, message.out, nil) if err != nil { t.Errorf("#%d,%d error: %s", i, j, err) } else if !bytes.Equal(out, message.in) { t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in) } // Decrypt with blinding. out, err = DecryptOAEP(sha1, random, private, message.out, nil) if err != nil { t.Errorf("#%d,%d (blind) error: %s", i, j, err) } else if !bytes.Equal(out, message.in) { t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in) } } if testing.Short() { break } } }
func main() { in, _ := os.Open("465.in") defer in.Close() out, _ := os.Create("465.out") defer out.Close() var s1, s2 string var op byte var i1, i2, i3 big.Int var maxInt = big.NewInt(math.MaxInt32) for { if _, err := fmt.Fscanf(in, "%s %c %s", &s1, &op, &s2); err != nil { break } fmt.Fprintf(out, "%s %c %s\n", s1, op, s2) i1.SetString(s1, 10) if i1.Cmp(maxInt) > 0 { fmt.Fprintln(out, "first number too big") } i2.SetString(s2, 10) if i2.Cmp(maxInt) > 0 { fmt.Fprintln(out, "second number too big") } if op == '+' { i3.Add(&i1, &i2) } else { i3.Mul(&i1, &i2) } if i3.Cmp(maxInt) > 0 { fmt.Fprintln(out, "result too big") } } }
func main() { var iban string var r, s, t, st []string u := new(big.Int) v := new(big.Int) w := new(big.Int) iban = "GB82 TEST 1234 5698 7654 32" r = strings.Split(iban, " ") s = strings.Split(r[0], "") t = strings.Split(r[1], "") st = []string{strconv.Itoa(sCode[t[0]]), strconv.Itoa(sCode[t[1]]), strconv.Itoa(sCode[t[2]]), strconv.Itoa(sCode[t[3]]), strings.Join(r[2:6], ""), strconv.Itoa(sCode[s[0]]), strconv.Itoa(sCode[s[1]]), strings.Join(s[2:4], ""), } u.SetString(strings.Join(st, ""), 10) v.SetInt64(97) w.Mod(u, v) if w.Uint64() == 1 && lCode[strings.Join(s[0:2], "")] == len(strings.Join(r, "")) { fmt.Printf("IBAN %s looks good!\n", iban) } else { fmt.Printf("IBAN %s looks wrong!\n", iban) } }
func q2() { n := new(big.Int) a := new(big.Int) asquared := new(big.Int) one := new(big.Int) x := new(big.Int) xsquared := new(big.Int) p := new(big.Int) q := new(big.Int) candidate := new(big.Int) n.SetString("648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877", 10) one.SetString("1", 10) a = mathutil.SqrtBig(n) for { a.Add(a, one) asquared.Mul(a, a) xsquared.Sub(asquared, n) x = mathutil.SqrtBig(xsquared) p.Sub(a, x) q.Add(a, x) if candidate.Mul(p, q).Cmp(n) == 0 { fmt.Println(p.String()) break } } }
func main() { var a, b string fmt.Scan(&a, &b) start := time.Now() /** SetString(a string,base int)-----将输入的字符串处理为BigInt ** The base argument must be 0 or a value from 2 through MaxBase. ** If the base is 0,the string prefix determines the actual conversion base. ** A prefix of “0x” or “0X” selects base 16; ** the “0” prefix selects base 8, and a “0b” or “0B” prefix selects ** base 2. Otherwise the selected base is 10. ** 例如:输入的字符串为"1234...",表示该字符串为10进制,base=10; ** 输入的字符串为"0x10ac1...",表示该字符串为16进制,base=16 ** base开始取0时,当输入的字符串为"0x101...",前缀为"0x",表示该字符串为16 ** 进制,所以base的实际值为16 **/ c := new(big.Int) d := new(big.Int) e := new(big.Int) c.SetString(a, 10) d.SetString(b, 10) e.Mul(c, d) fmt.Println(e) duration := time.Since(start) fmt.Printf(" %vms\n", duration.Seconds()*1000) }
func main() { // Open file for read fd, err := os.Open("numbers.txt") chk(err) defer fd.Close() // Line by line reader scanner := bufio.NewScanner(fd) scanner.Split(bufio.ScanLines) // Use standart library - big Integers bigSum := new(big.Int) for scanner.Scan() { ns := scanner.Text() bigInt := new(big.Int) bigInt.SetString(ns, 10) // Convert readed decimal string to big.Int bigSum.Add(bigSum, bigInt) } answerString := bigSum.String() fmt.Println("Result:", answerString, len(answerString)) fmt.Println("Answer:", answerString[0:10]) }
// makeDecimalFromMandE reconstructs the decimal from the mantissa M and // exponent E. func makeDecimalFromMandE(negative bool, e int, m []byte, tmp []byte) decimal.Decimal { // ±dddd. b := tmp[:0] if n := len(m)*2 + 1; cap(b) < n { b = make([]byte, 0, n) } if negative { b = append(b, '-') } for i, v := range m { t := int(v) if i == len(m) { t-- } t /= 2 b = append(b, byte(t/10)+'0', byte(t%10)+'0') } // We unsafely convert the []byte to a string to avoid the usual allocation // when converting to a string. bi := new(big.Int) bi, ok := bi.SetString(*(*string)(unsafe.Pointer(&b)), 10) if !ok { panic("could not set big.Int's string value") } exp := 2*e - len(b) if negative { exp++ } return decimal.NewFromBigInt(bi, int32(exp)) }
func problem55() string { reverseBig := func(b *big.Int) *big.Int { str := b.String() lenStr := len(str) strRev := make([]rune, lenStr) for i, r := range str { strRev[lenStr-1-i] = r } bReversed := new(big.Int) bReversed.SetString(string(strRev), 10) return bReversed } count := 0 const iMax, jMax = 10000, 51 for i := 1; i < iMax; i++ { ib := NewBig(i) count++ for j := 0; j < jMax; j++ { ib.Add(ib, reverseBig(ib)) // compute next Lychrel if IsBigPalindrome(ib) { count-- break } } } return itoa(count) }
func main() { in, _ := os.Open("10183.in") defer in.Close() out, _ := os.Create("10183.out") defer out.Close() var a, b string var n1, n2 big.Int l := len(p) for { if fmt.Fscanf(in, "%s%s", &a, &b); a == "0" && b == "0" { break } n1.SetString(a, 10) n2.SetString(b, 10) c := 0 for i := 1; i < l; i++ { if p[i].Cmp(&n1) >= 0 && p[i].Cmp(&n2) <= 0 { c++ } if p[i].Cmp(&n2) > 0 { break } } fmt.Fprintln(out, c) } }
// NewFromString returns a new Decimal from a string representation. // // Example: // // d, err := NewFromString("-123.45") // d2, err := NewFromString(".0001") // func NewFromString(value string) (Decimal, error) { var intString string var exp int32 parts := strings.Split(value, ".") if len(parts) == 1 { // There is no decimal point, we can just parse the original string as // an int intString = value exp = 0 } else if len(parts) == 2 { intString = parts[0] + parts[1] expInt := -len(parts[1]) if expInt < math.MinInt32 { // NOTE(vadim): I doubt a string could realistically be this long return Decimal{}, fmt.Errorf("can't convert %s to decimal: fractional part too long", value) } exp = int32(expInt) } else { return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value) } dValue := new(big.Int) _, ok := dValue.SetString(intString, 10) if !ok { return Decimal{}, fmt.Errorf("can't convert %s to decimal", value) } return Decimal{ value: dValue, exp: exp, }, nil }
// MakeConst makes an ideal constant from a literal // token and the corresponding literal string. func MakeConst(tok token.Token, lit string) Const { switch tok { case token.INT: var x big.Int _, ok := x.SetString(lit, 0) assert(ok) return Const{&x} case token.FLOAT: var y big.Rat _, ok := y.SetString(lit) assert(ok) return Const{&y} case token.IMAG: assert(lit[len(lit)-1] == 'i') var im big.Rat _, ok := im.SetString(lit[0 : len(lit)-1]) assert(ok) return Const{cmplx{big.NewRat(0, 1), &im}} case token.CHAR: assert(lit[0] == '\'' && lit[len(lit)-1] == '\'') code, _, _, err := strconv.UnquoteChar(lit[1:len(lit)-1], '\'') assert(err == nil) return Const{big.NewInt(int64(code))} case token.STRING: s, err := strconv.Unquote(lit) assert(err == nil) return Const{s} } panic("unreachable") }
func TestJwksSerializationPadding(t *testing.T) { x := new(big.Int) y := new(big.Int) e := &EssentialHeader{} e.KeyType = jwa.EC x.SetString("123520477547912006148785171019615806128401248503564636913311359802381551887648525354374204836279603443398171853465", 10) y.SetString("13515585925570416130130241699780319456178918334914981404162640338265336278264431930522217750520011829472589865088261", 10) pubKey := &ecdsa.PublicKey{ Curve: elliptic.P384(), X: x, Y: y, } jwkPubKey := NewEcdsaPublicKey(pubKey) jwkPubKey.EssentialHeader = e jwkJSON, err := json.Marshal(jwkPubKey) if !assert.NoError(t, err, "JWK Marshalled") { return } _, err = Parse(jwkJSON) if !assert.NoError(t, err, "JWK Parsed") { return } }
func TestGenerateGUID(t *testing.T) { idReader = rand.New(rand.NewSource(0)) for i := 0; i < 1000; i++ { guid := NewID() var i big.Int _, ok := i.SetString(guid, randomIDBase) if !ok { t.Fatal("id should be base 36", i, guid) } // To ensure that all identifiers are fixed length, we make sure they // get padded out to 25 characters, which is the maximum for the base36 // representation of 128-bit identifiers. // // For academics, f5lxx1zz5pnorynqglhzmsp33 == 2^128 - 1. This value // was calculated from floor(log(2^128-1, 36)) + 1. // // See http://mathworld.wolfram.com/NumberLength.html for more information. if len(guid) != maxRandomIDLength { t.Fatalf("len(%s) != %v", guid, maxRandomIDLength) } } }
func main() { var s string var n, two, tmp big.Int two.SetInt64(2) in, _ := os.Open("10519.in") defer in.Close() out, _ := os.Create("10519.out") defer out.Close() for { if _, err := fmt.Fscanf(in, "%s", &s); err != nil { break } if s == "0" { fmt.Fprintln(out, 1) continue } n.SetString(s, 10) tmp.Mul(&n, &n) tmp.Sub(&tmp, &n) tmp.Add(&tmp, &two) fmt.Fprintln(out, &tmp) } }
func HandleRegisterBasic(w http.ResponseWriter, r *http.Request) { fmt.Println("HandleRegisterBasic") tmpCurve := elliptic.P256() r.ParseMultipartForm(int64(100)) step := strings.TrimSpace(r.PostFormValue("step")) //state := strings.TrimSpace(r.PostFormValue("state")) if step == "0" { //fmt.Println(step, ":", state) w.Header().Set("Content-Type", "application/json") preInfo, _ := json.Marshal(PreInfo{tmpCurve.Params().Gx.String(), tmpCurve.Params().Gy.String(), tmpCurve.Params().P.String(), tmpCurve.Params().B.String(), tmpCurve.Params().N.String()}) //fmt.Println(string(preInfo)) io.WriteString(w, string(preInfo)) } if step == "1" { //fmt.Println(step, "::", state) pubKey := strings.TrimSpace(r.PostFormValue("pub_key")) fmt.Println(pubKey) uname := strings.TrimSpace(r.PostFormValue("uname")) key := strings.Split(pubKey, ",") pX := new(big.Int) pY := new(big.Int) pX.SetString(key[0], 10) pY.SetString(key[1], 10) dataB = elliptic.Marshal(tmpCurve, pX, pY) fmt.Println(">>>>>>>", uname) fmt.Println(">>>>>>>", dataB) storeData(uname, dataB) _, _ = getData(uname) } }
// Converts a number to a binary byte slice // i.e. 4 => [0,0,0,4] // 256 => [0,0,1,0] // or in the case of 64 // 4 = > [0,0,0,0,0,0,0,4] func makeBinary(value interface{}) []byte { var z []byte var val uint64 amount := 4 if v, ok := value.(uint64); ok { amount = 8 val = v } else if v, ok := value.(uint32); ok { val = uint64(v) } else { log.Panic("makeBinary requires a value that's either a uint32 or an uint64, got:", value) } str := strconv.FormatUint(val, 10) number := new(big.Int) number.SetString(str, 10) template := make([]byte, amount) x := number.Bytes() z = append(template[:(amount-len(x))], x...) return z }
func (n *Number) UnmarshalJSON(data []byte) error { input := strings.TrimSpace(string(data)) if len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' { input = input[1 : len(input)-1] } if len(input) == 0 { *n = Number(latestBlockNumber.Int64()) return nil } in := new(big.Int) _, ok := in.SetString(input, 0) if !ok { // test if user supplied string tag return fmt.Errorf(`invalid number %s`, data) } if in.Cmp(earliestBlockNumber) >= 0 && in.Cmp(maxBlockNumber) <= 0 { *n = Number(in.Int64()) return nil } return fmt.Errorf("blocknumber not in range [%d, %d]", earliestBlockNumber, maxBlockNumber) }
func (d *decoder) parse_int_interface() (ret interface{}) { start := d.offset - 1 d.read_until('e') if d.buf.Len() == 0 { panic(&SyntaxError{ Offset: start, What: errors.New("empty integer value"), }) } n, err := strconv.ParseInt(d.buf.String(), 10, 64) if ne, ok := err.(*strconv.NumError); ok && ne.Err == strconv.ErrRange { i := new(big.Int) _, ok := i.SetString(d.buf.String(), 10) if !ok { panic(&SyntaxError{ Offset: start, What: errors.New("failed to parse integer"), }) } ret = i } else { check_for_int_parse_error(err, start) ret = n } d.buf.Reset() return }
// Test marshaling back and forth between string and int // Pretty much a sanity check for further tests func TestStringMarshal(t *testing.T) { for _, tc := range idTestCases { i := new(big.Int) i.SetString(tc.base10, 10) assert.Equal(t, tc.base10, i.String()) } }
func (s *MySuite) TestComplexStructWithNestingAndPointer(c *C) { reader, err := Open("test-data/test-data/MaxMind-DB-test-decoder.mmdb") c.Assert(err, IsNil) var result TestPointerType err = reader.Lookup(net.ParseIP("::1.1.1.0"), &result) c.Assert(err, IsNil) c.Assert(*result.Array, DeepEquals, []uint{uint(1), uint(2), uint(3)}) c.Assert(*result.Boolean, Equals, true) c.Assert(*result.Bytes, DeepEquals, []byte{0x00, 0x00, 0x00, 0x2a}) c.Assert(*result.Double, Equals, 42.123456) c.Assert(*result.Float, Equals, float32(1.1)) c.Assert(*result.Int32, Equals, int32(-268435456)) c.Assert(result.Map.MapX.ArrayX, DeepEquals, []int{7, 8, 9}) c.Assert(result.Map.MapX.UTF8StringX, Equals, "hello") c.Assert(*result.Uint16, Equals, uint16(100)) c.Assert(*result.Uint32, Equals, uint32(268435456)) c.Assert(**result.Uint64, Equals, uint64(1152921504606846976)) c.Assert(*result.Utf8String, Equals, "unicode! ☯ - ♫") bigInt := new(big.Int) bigInt.SetString("1329227995784915872903807060280344576", 10) c.Assert(result.Uint128, DeepEquals, bigInt) c.Assert(reader.Close(), IsNil) }
// Compile instruction // // Attempts to compile and parse the given instruction in "s" // and returns the byte sequence func CompileInstr(s interface{}) ([]byte, error) { switch s := s.(type) { case vm.OpCode: return []byte{byte(s)}, nil case string: str := s // Check for pre formatted byte array // Jumps are preformatted if []byte(str)[0] == 0 { return []byte(str), nil } num := new(big.Int) _, success := num.SetString(str, 0) // Assume regular bytes during compilation if !success { num.SetBytes([]byte(str)) } return num.Bytes(), nil case int: return big.NewInt(int64(s)).Bytes(), nil case []byte: return new(big.Int).SetBytes(s).Bytes(), nil } return nil, nil }
func CompileInstr(s interface{}) ([]byte, error) { switch s.(type) { case string: str := s.(string) isOp := IsOpCode(str) if isOp { return []byte{OpCodes[str]}, nil } num := new(big.Int) _, success := num.SetString(str, 0) // Assume regular bytes during compilation if !success { num.SetBytes([]byte(str)) } return num.Bytes(), nil case int: return big.NewInt(int64(s.(int))).Bytes(), nil case []byte: return BigD(s.([]byte)).Bytes(), nil } return nil, nil }
func TestNewSession(t *testing.T) { gp, err := GetGroupParameters(1024) if err != nil { t.Error(err) } config := new(SRPConfig).New(gp, testh, testgen) config.abgen = testagen sess, err := new(SRPClientSession).New("alice", config) if err != nil { t.Error(err) } var biga big.Int biga.SetString("61D5E490F6F1B79547B0704C436F523DD0E560F0C64115BB72557EC44352E8903211C04692272D8B2D1A5358A2CF1B6E0BFCF99F921530EC8E39356179EAE45E42BA92AEACED825171E1E8B9AF6D9C03E1327F44BE087EF06530E69F66615261EEF54073CA11CF5858F0EDFDFE15EFEAB349EF5D76988A3672FAC47B0769447B", 16) if !bytes.Equal(biga.Bytes(), sess.biga.Bytes()) { t.Errorf("Public ephemeral value A incorrect.\n Expected: %X\n Got: %X", biga.Bytes(), sess.biga.Bytes()) } if sess.i != "alice" { t.Error("Username not correctly set.") } sess, err = new(SRPClientSession).New("", config) if err == nil { t.Error("Not properly reporting error on empty username.") } }
// ParseDecimal returns a new Decimal from a string representation. // // Example: // // d, err := ParseDecimal("-123.45") // d2, err := ParseDecimal(".0001") // func ParseDecimal(value string) (Decimal, error) { var intString string var exp int32 parts := strings.Split(value, ".") if len(parts) == 1 { // There is no decimal point, we can just parse the original string as // an int. intString = value exp = 0 } else if len(parts) == 2 { intString = parts[0] + parts[1] expInt := -len(parts[1]) exp = int32(expInt) } else { return Decimal{}, fmt.Errorf("can't convert %s to decimal: too many .s", value) } dValue := new(big.Int) _, ok := dValue.SetString(intString, 10) if !ok { return Decimal{}, fmt.Errorf("can't convert %s to decimal", value) } val := Decimal{ value: dValue, exp: exp, fracDigits: fracDigitsDefault(exp), } if exp < -MaxFractionDigits { val = val.rescale(-MaxFractionDigits) } return val, nil }
// Tests v.New() with a simple hash function and a given salt // checks output with test vector from appendix of RFC 5054 func TestSimpleHashSalt(t *testing.T) { testgp, err := GetGroupParameters(1024) if err != nil { t.Error("Error: ", err) } config := new(SRPConfig).New(testgp, testh, testgen) _, err = v.New("alice", "alice:password123", 32, config) if err == nil { t.Logf("Verifier is %X.\nSalt is %X.\n", v.Verifier.Bytes(), v.Salt.Bytes()) } else { t.Error("Error: ", err) } var correctv, corrects big.Int correctv.SetString("7E273DE8696FFC4F4E337D05B4B375BEB0DDE1569E8FA00A9886D8129BADA1F1822223CA1A605B530E379BA4729FDC59F105B4787E5186F5C671085A1447B52A48CF1970B4FB6F8400BBF4CEBFBB168152E08AB5EA53D15C1AFF87B2B9DA6E04E058AD51CC72BFC9033B564E26480D78E955A5E29E7AB245DB2BE315E2099AFB", 16) corrects.SetString("BEB25379D1A8581EB5A727673A2441EE", 16) if !bytes.Equal(correctv.Bytes(), v.Verifier.Bytes()) { t.Errorf("Error: Incorrect verifier.\nExpected: %X\nGot: %X", correctv.Bytes(), v.Verifier.Bytes()) } if !bytes.Equal(corrects.Bytes(), v.Salt.Bytes()) { t.Error("Error: recieved incorrect salt.") } if v.I != "alice" { t.Errorf("Error: username should be set to alice. Got %v", v.I) } }
// Generates and opens a temporary file with a defined prefix and suffix // This is the same api as ioutil.TempFile accept it accepts a suffix // TODO: see if this is too slow func TempFile(dir, prefix string, suffix string) (f *os.File, err error) { if dir == "" { dir = os.TempDir() } // The maximum size of random file count // TODO: see if we can do this at package scope somehow var maxRand *big.Int = big.NewInt(0) maxRand.SetString("FFFFFFFFFFFFFFFF", 16) var randNum *big.Int for i := 0; i < 10000; i++ { // Generate random part of the path name randNum, err = rand.Int(rand.Reader, maxRand) if err != nil { return } // Transform to an int randString := hex.EncodeToString(randNum.Bytes()) // Attempt to open file and fail if it already exists name := filepath.Join(dir, prefix+randString+suffix) f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) if os.IsExist(err) { continue } break } return }
// finishReadingInteger tries parsing an int64, then a uint64, and finally a big.Int, // as required by the size of the value. func finishReadingInteger(xmlDecoder *xml.Decoder) (interface{}, error) { raw, err := readCharDataUntilEnd(xmlDecoder, integerStartElement.End()) if err != nil { return nil, err } var value interface{} value, err = strconv.ParseInt(raw, 10, 64) if err == nil { return value, nil } else if !isErrOutOfRange(err) { return nil, err } value, err = strconv.ParseUint(raw, 10, 64) if err == nil { return value, nil } else if !isErrOutOfRange(err) { return nil, err } var bigValue big.Int if _, ok := bigValue.SetString(raw, 10); ok { return bigValue, nil } return nil, fmt.Errorf("Could not parse '%s' as an integer.", raw) }
func str2big(hex string) *big.Int { var x big.Int _, ok := x.SetString(hex, 16) if !ok { panic("FOO") } return &x }
func bigIntFromStr(s string, base int) *big.Int { result := new(big.Int) result, success := result.SetString(s, 10) if !success { die(false, "Error: cannot create big int from string '%s'", s) } return result }