// 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 }
// 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 }
// (n - 2^(k-1)) mod 2^m func calcLastFinger(n []byte, k int) (string, []byte) { // convert the n to a bigint nBigInt := big.Int{} nBigInt.SetBytes(n) // get the right addend, i.e. 2^(k-1) two := big.NewInt(2) addend := big.Int{} addend.Exp(two, big.NewInt(int64(k-1)), nil) addend.Mul(&addend, big.NewInt(-1)) //Soustraction neg := big.Int{} neg.Add(&addend, &nBigInt) // calculate 2^m m := 160 ceil := big.Int{} ceil.Exp(two, big.NewInt(int64(m)), nil) // apply the mod result := big.Int{} result.Mod(&neg, &ceil) resultBytes := result.Bytes() resultHex := fmt.Sprintf("%x", resultBytes) return resultHex, resultBytes }
// getMPI returns the length encoded Int and the next slice. func getMPI(b []byte) (*big.Int, []byte) { p := new(big.Int) plen := (uint64(b[0])*256 + uint64(b[1]) + 7) >> 3 p.SetBytes(b[2 : plen+2]) b = b[plen+2:] return p, b }
// (n + 2^(k-1)) mod (2^m) func calcFinger(n []byte, k int, m int) (string, []byte) { // convert the n to a bigint nBigInt := big.Int{} nBigInt.SetBytes(n) // get the right addend, i.e. 2^(k-1) two := big.NewInt(2) addend := big.Int{} addend.Exp(two, big.NewInt(int64(k-1)), nil) // calculate sum sum := big.Int{} sum.Add(&nBigInt, &addend) // calculate 2^m ceil := big.Int{} ceil.Exp(two, big.NewInt(int64(m)), nil) // apply the mod result := big.Int{} result.Mod(&sum, &ceil) resultBytes := result.Bytes() resultHex := fmt.Sprintf("%x", resultBytes) return resultHex, resultBytes }
func main() { for _, c := range curves { f, err := os.Create(c.params.Name) if err != nil { fmt.Fprintf(os.Stderr, "error creating file %s: %s", c.params.Name, err) os.Exit(-1) } h := sha3.NewShake256() h.Write([]byte(c.params.Name)) h.Write([]byte(": doubly prime")) buf := make([]byte, c.bits) v := new(big.Int) fmt.Fprintf(f, "[") for i := 0; i < 1000; i++ { if i != 0 { fmt.Fprintf(f, ",") } for trial := 0; ; trial++ { h.Read(buf) v.SetBytes(buf) if v.Cmp(c.params.P) == -1 { break } } fmt.Fprintf(f, "%d", v) } fmt.Fprintf(f, "]\n") f.Close() } }
func TestPad(t *testing.T) { private, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil || private == nil { t.Fatal("Can't gen private key %s\n", err) } public := &private.PublicKey var a [9]byte copy(a[0:8], "IDENTITY") seed := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} encrypted_secret, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, public, seed, a[0:9]) if err != nil { t.Fatal("Can't encrypt ", err) } fmt.Printf("encrypted_secret: %x\n", encrypted_secret) decrypted_secret, err := rsa.DecryptOAEP(sha1.New(), rand.Reader, private, encrypted_secret, a[0:9]) if err != nil { t.Fatal("Can't decrypt ", err) } fmt.Printf("decrypted_secret: %x\n", decrypted_secret) var N *big.Int var D *big.Int var x *big.Int var z *big.Int N = public.N D = private.D x = new(big.Int) z = new(big.Int) x.SetBytes(encrypted_secret) z = z.Exp(x, D, N) decrypted_pad := z.Bytes() fmt.Printf("decrypted_pad : %x\n", decrypted_pad) }
// Sign signs a blinded message func (signer *Signer) Sign(blindmessage *BlindMessageInt, privateParams *SignRequestPrivateInt) (signature *BlindSignatureInt, err error) { if privateParams.IsUsed { return nil, eccutil.ErrParamReuse } //cparams := signer.curve.curve.Params() privkeyInt := new(big.Int) privkeyInt = privkeyInt.SetBytes(signer.privkey) _, err = signer.curve.TestParams(privkeyInt, blindmessage.M1, blindmessage.M2, privateParams.ScalarRs1, privateParams.ScalarKs1, privateParams.ScalarLs1, privateParams.ScalarRs2, privateParams.ScalarKs2, privateParams.ScalarLs2) if err != nil { return nil, err // Should never fire } mt1 := eccutil.ManyMult(privkeyInt, blindmessage.M1) // SigPriv * m1 mt2 := eccutil.ManyMult(privkeyInt, blindmessage.M2) // SigPriv * m2 ms1 := eccutil.ManyMult(privateParams.ScalarRs1, privateParams.ScalarKs1, privateParams.ScalarLs1) // rs1 * k1 * l1 ms2 := eccutil.ManyMult(privateParams.ScalarRs2, privateParams.ScalarKs2, privateParams.ScalarLs2) // rs2 * k2 * l2 ss1, ss2 := new(big.Int), new(big.Int) ss1 = ss1.Sub(mt1, ms1) // (SigPriv * m1) - (rs1 * k1 * l1) ss2 = ss2.Sub(mt2, ms2) // (SigPriv * m2) - (rs2 * k2 * l2) ss1 = ss1.Mod(ss1, signer.curve.Params.N) // ss1 = (SigPriv * m1 - rs1 * k1 * l1) mod N ss2 = ss2.Mod(ss2, signer.curve.Params.N) // ss2 = (SigPriv * m2 - rs2 * k2 * l2) mod N signaturet := new(BlindSignatureInt) signaturet.ScalarS1 = ss1 signaturet.ScalarS2 = ss2 return signaturet, nil }
func (p *PrivateKeys) addRemoteKey(remote []byte, clientPacket []byte, serverPacket []byte) SharedKeys { remote_be := new(big.Int) remote_be.SetBytes(remote) shared_key := powm(remote_be, p.privateKey, p.prime) data := make([]byte, 0, 100) mac := hmac.New(sha1.New, shared_key.Bytes()) for i := 1; i < 6; i++ { mac.Write(clientPacket) mac.Write(serverPacket) mac.Write([]byte{uint8(i)}) data = append(data, mac.Sum(nil)...) mac.Reset() } mac = hmac.New(sha1.New, data[0:0x14]) mac.Write(clientPacket) mac.Write(serverPacket) return SharedKeys{ challenge: mac.Sum(nil), sendKey: data[0x14:0x34], recvKey: data[0x34:0x54], } }
// Put implements storage.Contacts. func (c *contacts) Put(name string, key *sf.PublicKey) error { if len(name) == 0 { return errgo.New("empty key name") } return c.db.Update(func(tx *bolt.Tx) error { contactsBucket, err := tx.CreateBucketIfNotExists([]byte("contacts")) if err != nil { return errgo.Mask(err) } err = contactsBucket.Put(key[:], []byte(name)) if err != nil { return errgo.Mask(err) } keysBucket, err := contactsBucket.CreateBucketIfNotExists([]byte(name)) if err != nil { return errgo.Mask(err) } lastSeqBytes, _ := keysBucket.Cursor().Last() var seq big.Int seq.SetBytes(lastSeqBytes) seq.Add(&seq, bigOne) err = keysBucket.Put(seq.Bytes(), key[:]) if err != nil { return errgo.Mask(err) } return nil }) }
// Returns a big integer with the given nb bytes func RandomBigInt(nb int) *big.Int { b := make([]byte, nb) rand.Read(b) r := new(big.Int) r.SetBytes(b) return r }
func (dag *Dagger) Node(L uint64, i uint64) *big.Int { if L == i { return dag.hash } var m *big.Int if L == 9 { m = big.NewInt(16) } else { m = big.NewInt(3) } sha := sha3.NewKeccak256() sha.Reset() d := sha3.NewKeccak256() b := new(big.Int) ret := new(big.Int) for k := 0; k < int(m.Uint64()); k++ { d.Reset() d.Write(dag.hash.Bytes()) d.Write(dag.xn.Bytes()) d.Write(big.NewInt(int64(L)).Bytes()) d.Write(big.NewInt(int64(i)).Bytes()) d.Write(big.NewInt(int64(k)).Bytes()) b.SetBytes(Sum(d)) pk := b.Uint64() & ((1 << ((L - 1) * 3)) - 1) sha.Write(dag.Node(L-1, pk).Bytes()) } ret.SetBytes(Sum(sha)) return ret }
func (dag *Dagger) Eval(N *big.Int) *big.Int { pow := common.BigPow(2, 26) dag.xn = pow.Div(N, pow) sha := sha3.NewKeccak256() sha.Reset() ret := new(big.Int) for k := 0; k < 4; k++ { d := sha3.NewKeccak256() b := new(big.Int) d.Reset() d.Write(dag.hash.Bytes()) d.Write(dag.xn.Bytes()) d.Write(N.Bytes()) d.Write(big.NewInt(int64(k)).Bytes()) b.SetBytes(Sum(d)) pk := (b.Uint64() & 0x1ffffff) sha.Write(dag.Node(9, pk).Bytes()) } return ret.SetBytes(Sum(sha)) }
// powerOffset computes the offset by (n + 2^exp) % (2^mod) func powerOffset(id []byte, exp int, mod int) []byte { // Copy the existing slice off := make([]byte, len(id)) copy(off, id) // Convert the ID to a bigint idInt := big.Int{} idInt.SetBytes(id) // Get the offset two := big.NewInt(2) offset := big.Int{} offset.Exp(two, big.NewInt(int64(exp)), nil) // Sum sum := big.Int{} sum.Add(&idInt, &offset) // Get the ceiling ceil := big.Int{} ceil.Exp(two, big.NewInt(int64(mod)), nil) // Apply the mod idInt.Mod(&sum, &ceil) // Add together return idInt.Bytes() }
/* KeyedPRF is a psuedo random function. It hashes the input, pads it to the correct output length, and then encrypts it with AES. Finally it checks that the result is within the desired range. If it is it returns the value as a long integer, if it isn't, it increments a nonce in the input and recalculates until it finds an integer in the given range */ func keyedPRFBig(key []byte, r *big.Int, x int) (*big.Int, error) { aesBlockEncrypter, err := aes.NewCipher(key) if err != nil { return nil, err } aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, make([]byte, aes.BlockSize)) hash := sha256.New() var num big.Int result := make([]byte, r.BitLen()>>3) for nonce := 0; ; nonce++ { hash.Reset() hash.Write([]byte(strconv.Itoa(x + nonce))) h := hash.Sum(nil) if r.BitLen() > 32*8 { len := 32 - uint((r.BitLen()+7)>>3) h = append(h, make([]byte, len)...) } if r.BitLen() < 32*8 { len := uint((r.BitLen() + 7) >> 3) h = h[:len] } aesEncrypter.XORKeyStream(result, h) num.SetBytes(result) if num.Cmp(r) < 0 { break } } return &num, 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 (d *decoder) decodeUint128(size uint, offset uint) (*big.Int, uint, error) { newOffset := offset + size val := new(big.Int) val.SetBytes(d.buffer[offset:newOffset]) return val, newOffset, nil }
func generateKeys() privateKeys { private := new(big.Int) private.SetBytes(randomVec(95)) nonce := randomVec(0x10) return generateKeysFromPrivate(private, nonce) }
// Base58Encode encodes a byte slice to a modified base58 string. func Base58Encode(b []byte, alphabet string) string { x := new(big.Int) x.SetBytes(b) answer := make([]byte, 0) for x.Cmp(bigZero) > 0 { mod := new(big.Int) x.DivMod(x, bigRadix, mod) answer = append(answer, alphabet[mod.Int64()]) } // leading zero bytes for _, i := range b { if i != 0 { break } answer = append(answer, alphabet[0]) } // reverse alen := len(answer) for i := 0; i < alen/2; i++ { answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i] } return string(answer) }
func CreateID(d *schema.ResourceData, meta interface{}) error { byteLength := d.Get("byte_length").(int) bytes := make([]byte, byteLength) n, err := rand.Reader.Read(bytes) if n != byteLength { return fmt.Errorf("generated insufficient random bytes") } if err != nil { return fmt.Errorf("error generating random bytes: %s", err) } b64Str := base64.RawURLEncoding.EncodeToString(bytes) hexStr := hex.EncodeToString(bytes) int := big.Int{} int.SetBytes(bytes) decStr := int.String() d.SetId(b64Str) d.Set("b64", b64Str) d.Set("hex", hexStr) d.Set("dec", decStr) return nil }
func wipeBigInt(k *big.Int) { if k == nil { return } k.SetBytes(zeroes(len(k.Bytes()))) }
func (c *Conversation) processSMP4(mpis []*big.Int) error { if len(mpis) != 3 { return errors.New("otr: incorrect number of arguments in SMP4 message") } rb := mpis[0] cr := mpis[1] d7 := mpis[2] h := sha256.New() r := new(big.Int).Exp(c.smp.qaqb, d7, p) s := new(big.Int).Exp(rb, cr, p) r.Mul(r, s) r.Mod(r, p) s.Exp(g, d7, p) t := new(big.Int).Exp(c.smp.g3b, cr, p) s.Mul(s, t) s.Mod(s, p) t.SetBytes(hashMPIs(h, 8, s, r)) if t.Cmp(cr) != 0 { return errors.New("otr: ZKP cR failed in SMP4 message") } r.Exp(rb, c.smp.a3, p) if r.Cmp(c.smp.papb) != 0 { return smpFailureError } return nil }
func (c *Conversation) processSMP1(mpis []*big.Int) error { if len(mpis) != 6 { return errors.New("otr: incorrect number of arguments in SMP1 message") } g2a := mpis[0] c2 := mpis[1] d2 := mpis[2] g3a := mpis[3] c3 := mpis[4] d3 := mpis[5] h := sha256.New() r := new(big.Int).Exp(g, d2, p) s := new(big.Int).Exp(g2a, c2, p) r.Mul(r, s) r.Mod(r, p) t := new(big.Int).SetBytes(hashMPIs(h, 1, r)) if c2.Cmp(t) != 0 { return errors.New("otr: ZKP c2 incorrect in SMP1 message") } r.Exp(g, d3, p) s.Exp(g3a, c3, p) r.Mul(r, s) r.Mod(r, p) t.SetBytes(hashMPIs(h, 2, r)) if c3.Cmp(t) != 0 { return errors.New("otr: ZKP c3 incorrect in SMP1 message") } c.smp.g2a = g2a c.smp.g3a = g3a return nil }
// splitK returns a balanced length-two representation of k and their signs. // This is algorithm 3.74 from [GECC]. // // One thing of note about this algorithm is that no matter what c1 and c2 are, // the final equation of k = k1 + k2 * lambda (mod n) will hold. This is // provable mathematically due to how a1/b1/a2/b2 are computed. // // c1 and c2 are chosen to minimize the max(k1,k2). func (curve *KoblitzCurve) splitK(k []byte) ([]byte, []byte, int, int) { // All math here is done with big.Int, which is slow. // At some point, it might be useful to write something similar to // FieldVal but for N instead of P as the prime field if this ends up // being a bottleneck. bigIntK := new(big.Int) c1, c2 := new(big.Int), new(big.Int) tmp1, tmp2 := new(big.Int), new(big.Int) k1, k2 := new(big.Int), new(big.Int) bigIntK.SetBytes(k) // c1 = round(b2 * k / n) from step 4. // Rounding isn't really necessary and costs too much, hence skipped c1.Mul(curve.b2, bigIntK) c1.Div(c1, curve.N) // c2 = round(b1 * k / n) from step 4 (sign reversed to optimize one step) // Rounding isn't really necessary and costs too much, hence skipped c2.Mul(curve.b1, bigIntK) c2.Div(c2, curve.N) // k1 = k - c1 * a1 - c2 * a2 from step 5 (note c2's sign is reversed) tmp1.Mul(c1, curve.a1) tmp2.Mul(c2, curve.a2) k1.Sub(bigIntK, tmp1) k1.Add(k1, tmp2) // k2 = - c1 * b1 - c2 * b2 from step 5 (note c2's sign is reversed) tmp1.Mul(c1, curve.b1) tmp2.Mul(c2, curve.b2) k2.Sub(tmp2, tmp1) // Note Bytes() throws out the sign of k1 and k2. This matters // since k1 and/or k2 can be negative. Hence, we pass that // back separately. return k1.Bytes(), k2.Bytes(), k1.Sign(), k2.Sign() }
func setBytesReverse(b *big.Int, d []byte) *big.Int { buf := make([]byte, len(d)) for i := 0; i < len(d); i++ { buf[len(d)-i-1] = d[i] } return b.SetBytes(buf) }
func (h *hasher) GetLoggregatorServerForAppId(appId string) string { var id, numberOfItems big.Int id.SetBytes([]byte(appId)) numberOfItems.SetInt64(int64(len(h.items))) id.Mod(&id, &numberOfItems) return h.items[id.Int64()] }
func (key Keypair) Decrypt(ciphertext []byte) []byte { dataInt := new(big.Int) dataInt.SetBytes(ciphertext) msg := new(big.Int).Exp(dataInt, key.D, key.N) return msg.Bytes() }
//example hash function func H(to_hash, salt []byte) big.Int { var x big.Int dk := pbkdf2.Key(to_hash, salt, 10000, 128, sha512.New) x.SetBytes(dk) return x }
func (key Keypair) Encrypt(plaintext []byte) []byte { dataInt := new(big.Int) dataInt.SetBytes(plaintext) msg := new(big.Int).Exp(dataInt, big.NewInt(int64(key.E)), key.N) return msg.Bytes() }
func (txn *NameAllocation) Verify(publicKey *ecdsa.PublicKey) bool { buf := bytes.NewBuffer([]byte{}) binary.Write(buf, binary.LittleEndian, sha1.Sum(append([]byte("ALLOCATE"), txn.Name...))) r := new(big.Int) s := new(big.Int) r.SetBytes(txn.SignatureR) s.SetBytes(txn.SignatureS) return ecdsa.Verify(publicKey, buf.Bytes(), r, s) }