예제 #1
0
func TestChaChaCorrectness(t *testing.T) {
	ec, dc := initChaCha(20)
	sample = bytes.Repeat(origin, 100)
	origin = bytes.Repeat(origin, 100)

	randChip("dec", sample, func(chip []byte) {
		ec.XORKeyStream(chip, chip)
	})

	dc.XORKeyStream(sample, sample)

	if !bytes.Equal(origin, sample) {
		dumpHex(sample, "result")
		dumpHex(origin, "origin")
		t.Fatalf("Incorrect result")
	}

	ec.XORKeyStream(sample, sample)

	randChip("dec", sample, func(chip []byte) {
		dc.XORKeyStream(chip, chip)
	})

	if !bytes.Equal(origin, sample) {
		dumpHex(sample, "result")
		dumpHex(origin, "origin")
		t.Fatalf("Incorrect result")
	}
}
예제 #2
0
파일: write_test.go 프로젝트: agelin/etf
func TestWriteAtom(t *testing.T) {
	c := new(Context)
	test := func(in Atom, shouldFail bool) {
		w := new(bytes.Buffer)
		if err := c.writeAtom(w, in); err != nil {
			if !shouldFail {
				t.Error(in, err)
			}
		} else if shouldFail {
			t.Error("err == nil (%v)", in)
		} else if v, err := c.Read(w); err != nil {
			t.Error(in, err)
		} else if l := w.Len(); l != 0 {
			t.Errorf("%v: buffer len %d", in, l)
		} else if v != in {
			t.Errorf("expected %v, got %v", in, v)
		}
	}

	test(Atom(""), false)
	test(Atom(bytes.Repeat([]byte{'a'}, math.MaxUint8)), false)
	test(Atom(bytes.Repeat([]byte{'a'}, math.MaxUint8+1)), false)
	test(Atom(bytes.Repeat([]byte{'a'}, math.MaxUint16)), false)
	test(Atom(bytes.Repeat([]byte{'a'}, math.MaxUint16+1)), true)
}
예제 #3
0
func TestUnencryptedSuffix(t *testing.T) {
	branch := TreeBranch{
		TreeItem{
			Key:   "foo_unencrypted",
			Value: "bar",
		},
	}
	tree := Tree{Branch: branch, Metadata: Metadata{UnencryptedSuffix: "_unencrypted"}}
	expected := TreeBranch{
		TreeItem{
			Key:   "foo_unencrypted",
			Value: "bar",
		},
	}
	cipher := aes.Cipher{}
	_, err := tree.Encrypt(bytes.Repeat([]byte("f"), 32), cipher)
	if err != nil {
		t.Errorf("Encrypting the tree failed: %s", err)
	}
	if !reflect.DeepEqual(tree.Branch, expected) {
		t.Errorf("Trees don't match: \ngot \t\t%+v,\n expected \t\t%+v", tree.Branch, expected)
	}
	_, err = tree.Decrypt(bytes.Repeat([]byte("f"), 32), cipher)
	if err != nil {
		t.Errorf("Decrypting the tree failed: %s", err)
	}
	if !reflect.DeepEqual(tree.Branch, expected) {
		t.Errorf("Trees don't match: \ngot\t\t\t%+v,\nexpected\t\t%+v", tree.Branch, expected)
	}
}
예제 #4
0
파일: bench_test.go 프로젝트: decred/dcrd
// BenchmarkDeserializeTxLarge performs a benchmark on how long it takes to
// deserialize a very large transaction.
func BenchmarkDeserializeTxLarge(b *testing.B) {
	bigTx := new(MsgTx)
	bigTx.Version = DefaultMsgTxVersion()
	inputsLen := 1000
	outputsLen := 2000
	bigTx.TxIn = make([]*TxIn, inputsLen)
	bigTx.TxOut = make([]*TxOut, outputsLen)
	for i := 0; i < inputsLen; i++ {
		bigTx.TxIn[i] = &TxIn{
			SignatureScript: bytes.Repeat([]byte{0x12}, 120),
		}
	}
	for i := 0; i < outputsLen; i++ {
		bigTx.TxOut[i] = &TxOut{
			PkScript: bytes.Repeat([]byte{0x34}, 30),
		}
	}
	bigTxB, err := bigTx.Bytes()
	if err != nil {
		b.Fatalf("%v", err.Error())
	}

	r := bytes.NewReader(bigTxB)
	var tx MsgTx
	for i := 0; i < b.N; i++ {
		r.Seek(0, 0)
		tx.Deserialize(r)
	}
}
예제 #5
0
func TestGetApproximateOffsetPlain(t *testing.T) {
	w := new(writer)
	o := &opt.Options{
		BlockSize:   1024,
		Compression: opt.NoCompression,
	}
	tw := NewWriter(w, o)
	tw.Append([]byte("k01"), []byte("hello"))
	tw.Append([]byte("k02"), []byte("hello2"))
	tw.Append([]byte("k03"), bytes.Repeat([]byte{'x'}, 10000))
	tw.Append([]byte("k04"), bytes.Repeat([]byte{'x'}, 200000))
	tw.Append([]byte("k05"), bytes.Repeat([]byte{'x'}, 300000))
	tw.Append([]byte("k06"), []byte("hello3"))
	tw.Append([]byte("k07"), bytes.Repeat([]byte{'x'}, 100000))
	if err := tw.Close(); err != nil {
		t.Fatal("error when finalizing table:", err.Error())
	}
	size := w.Len()
	r := &reader{*bytes.NewReader(w.Bytes())}
	tr := NewReader(r, int64(size), nil, o)
	// if err != nil {
	// 	t.Fatal("error when creating table reader instance:", err.Error())
	// }

	offsetBetween(t, tr, []byte("k0"), 0, 0)
	offsetBetween(t, tr, []byte("k01a"), 0, 0)
	offsetBetween(t, tr, []byte("k02"), 0, 0)
	offsetBetween(t, tr, []byte("k03"), 0, 0)
	offsetBetween(t, tr, []byte("k04"), 10000, 11000)
	offsetBetween(t, tr, []byte("k04a"), 210000, 211000)
	offsetBetween(t, tr, []byte("k05"), 210000, 211000)
	offsetBetween(t, tr, []byte("k06"), 510000, 511000)
	offsetBetween(t, tr, []byte("k07"), 510000, 511000)
	offsetBetween(t, tr, []byte("xyz"), 610000, 612000)
}
예제 #6
0
func TestNodeIDBase10(t *testing.T) {
	tests := [...]struct {
		bytes  []byte
		base10 *big.Int
	}{
		{
			make([]byte, 16),
			big.NewInt(0),
		},
		{
			append(make([]byte, 15), 1),
			big.NewInt(1),
		},
		{
			bytes.Repeat([]byte{0xff}, 16),
			new(big.Int).SetBytes(bytes.Repeat([]byte{0xff}, 16)),
		},
	}
	for i, test := range tests {
		id, err := NodeIDFromBytes(test.bytes)
		if err != nil {
			t.Errorf("test %v: unexpected error %v", i, err)
		}
		base10 := id.Base10()
		if base10.Cmp(test.base10) != 0 {
			t.Errorf("test %v: expected %v, got %v", i, test.base10, base10)
		}
	}
}
예제 #7
0
// NewForwardingMessage generates the a mix header containing the neccessary
// onion routing information required to propagate the message through the
// mixnet, eventually reaching the final node specified by 'identifier'. The
// onion encrypted message payload is then to be delivered to the specified 'dest'
// address.
func NewForwardingMessage(route []*btcec.PublicKey, dest LightningAddress,
	message []byte) (*ForwardingMessage, error) {
	routeLength := len(route)

	// Compute the mix header, and shared secerts for each hop. We pass in
	// the null destination and zero identifier in order for the final node
	// in the route to be able to distinguish the payload as addressed to
	// itself.
	mixHeader, secrets, err := NewMixHeader([]byte{nullDest}, zeroNode, route)
	if err != nil {
		return nil, err
	}

	// Now for the body of the message. The next-node ID is set to all
	// zeroes in order to notify the final hop that the message is meant for
	// them. m = 0^k || dest || msg || padding.
	var body [messageSize]byte
	n := copy(body[:], bytes.Repeat([]byte{0}, securityParameter))
	// TODO(roasbeef): destination vs identifier (node id) format.
	n += copy(body[n:], []byte(dest))
	n += copy(body[n:], message)
	// TODO(roasbeef): make pad and unpad functions.
	n += copy(body[n:], []byte{0x7f})
	n += copy(body[n:], bytes.Repeat([]byte{0xff}, messageSize-len(body)))

	// Now we construct the onion. Walking backwards from the last hop, we
	// encrypt the message with the shared secret for each hop in the path.
	onion := lionessEncode(generateKey("pi", secrets[routeLength-1]), body)
	for i := routeLength - 2; i >= 0; i-- {
		onion = lionessEncode(generateKey("pi", secrets[i]), onion)
	}

	return &ForwardingMessage{Header: mixHeader, Msg: onion}, nil
}
func BenchmarkPathPacketConstruction(b *testing.B) {
	route := make([]*btcec.PublicKey, NumMaxHops)
	for i := 0; i < NumMaxHops; i++ {
		privKey, err := btcec.NewPrivateKey(btcec.S256())
		if err != nil {
			b.Fatalf("unable to generate key: %v", privKey)
		}

		route[i] = privKey.PubKey()
	}

	var (
		err          error
		sphinxPacket *OnionPacket
	)

	var hopPayloads [][]byte
	for i := 0; i < len(route); i++ {
		payload := bytes.Repeat([]byte{byte('A' + i)}, HopPayloadSize)
		hopPayloads = append(hopPayloads, payload)
	}

	d, _ := btcec.PrivKeyFromBytes(btcec.S256(), bytes.Repeat([]byte{'A'}, 32))
	for i := 0; i < b.N; i++ {
		sphinxPacket, err = NewOnionPacket(route, d, hopPayloads, nil)
		if err != nil {
			b.Fatalf("unable to create packet: %v", err)
		}
	}

	s = sphinxPacket
}
예제 #9
0
파일: hci_test.go 프로젝트: jiyeyuran/gatt
func TestAdvertiseEIR(t *testing.T) {
	cases := []struct {
		adv     []byte
		scan    []byte
		want    string
		wanterr bool
	}{
		{adv: []byte{0x12, 0x34}, scan: []byte{0xAB, 0xCD}, want: "1234 abcd\n"},
		{scan: []byte{0xAB, 0xCD}, want: " abcd\n"},
		{adv: []byte{0x12, 0x34}, want: "1234 \n"},
		// data too long
		{adv: bytes.Repeat([]byte{0}, 32), wanterr: true},
		{scan: bytes.Repeat([]byte{0}, 32), wanterr: true},
	}

	shim := new(testshim)
	hci := newHCI(shim)
	for _, tt := range cases {
		shim.Buffer.Reset()
		err := hci.advertiseEIR(tt.adv, tt.scan)
		if tt.wanterr {
			if err != ErrEIRPacketTooLong {
				t.Errorf("AdvertiseEIR(%x, %x) got %v want ErrEIRPacketTooLong", tt.adv, tt.scan, err)
			}
			continue
		}
		if err != nil {
			t.Errorf("AdvertiseEIR(%x, %x) unexpected error: %v", tt.adv, tt.scan, err)
		}
		if got := shim.Buffer.String(); got != tt.want {
			t.Errorf("AdvertiseEIR(%x, %x): got %q want %q", tt.adv, tt.scan, got, tt.want)
		}
	}
}
예제 #10
0
func TestGrow(t *testing.T) {
	x := []byte{'x'}
	y := []byte{'y'}
	tmp := make([]byte, 72)
	for _, startLen := range []int{0, 100, 1000, 10000, 100000} {
		xBytes := bytes.Repeat(x, startLen)
		for _, growLen := range []int{0, 100, 1000, 10000, 100000} {
			buf := NewBuffer(xBytes)
			// If we read, this affects buf.off, which is good to test.
			readBytes, _ := buf.Read(tmp)
			buf.Grow(growLen)
			yBytes := bytes.Repeat(y, growLen)
			// Check no allocation occurs in write, as long as we're single-threaded.
			var m1, m2 runtime.MemStats
			runtime.ReadMemStats(&m1)
			buf.Write(yBytes)
			runtime.ReadMemStats(&m2)
			if runtime.GOMAXPROCS(-1) == 1 && m1.Mallocs != m2.Mallocs {
				t.Errorf("allocation occurred during write")
			}
			// Check that buffer has correct data.
			if !bytes.Equal(buf.Bytes()[0:startLen-readBytes], xBytes[readBytes:]) {
				t.Errorf("bad initial data at %d %d", startLen, growLen)
			}
			if !bytes.Equal(buf.Bytes()[startLen-readBytes:startLen-readBytes+growLen], yBytes) {
				t.Errorf("bad written data at %d %d", startLen, growLen)
			}
		}
	}
}
예제 #11
0
func buildFloors(b [][]byte, ln int) (ret [][]byte) {

	ret = make([][]byte, len(b)*2+1)

	for i := 0; i < len(b); i++ {
		v := make([]byte, ln, ln)
		copy(v, b[i])
		v = bytes.Replace(v, []byte{0}, []byte{' '}, -1)
		v = bytes.Replace(v, []byte{' '}, bytes.Repeat([]byte{' '}, 4), -1)
		v = bytes.Replace(v, []byte{'*'}, []byte("+---"), -1)
		v = bytes.Replace(v, []byte("- "), []byte("-+"), -1)
		ret[i*2] = v
		ret[i*2+1] = bytes.Repeat([]byte{' '}, ln*4)
	}

	ret[len(ret)-1] = make([]byte, len(ret[0]))
	copy(ret[len(ret)-1], ret[len(ret)-3])

	for i := len(ret) - 5; i >= 0; i -= 2 {
		for j, v := range ret[i] {
			if v == '-' && ret[i+2][j] == '-' {
				ret[i+2][j] = ' '
			}
		}
		ret[i+2] = bytes.Replace(ret[i+2], []byte(" + "), []byte("   "), -1)
		ret[i+2] = bytes.Replace(ret[i+2], []byte("-+-"), []byte("---"), -1)
	}
	ret[len(ret)-1] = bytes.Replace(ret[len(ret)-1], []byte("-+-"), []byte("---"), -1)
	ret[0] = bytes.Replace(ret[0], []byte("-+-"), []byte("---"), -1)

	return ret

}
예제 #12
0
// TestNumUnderlyingWrites tests that each Writer flush only makes one or two
// Write calls on its underlying io.Writer, depending on whether or not the
// flushed buffer was compressible.
func TestNumUnderlyingWrites(t *testing.T) {
	testCases := []struct {
		input []byte
		want  int
	}{
		{bytes.Repeat([]byte{'x'}, 100), 1},
		{bytes.Repeat([]byte{'y'}, 100), 1},
		{[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
	}

	var c writeCounter
	w := NewBufferedWriter(&c)
	defer w.Close()
	for i, tc := range testCases {
		c = 0
		if _, err := w.Write(tc.input); err != nil {
			t.Errorf("#%d: Write: %v", i, err)
			continue
		}
		if err := w.Flush(); err != nil {
			t.Errorf("#%d: Flush: %v", i, err)
			continue
		}
		if int(c) != tc.want {
			t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
			continue
		}
	}
}
예제 #13
0
파일: parser_test.go 프로젝트: guileen/xbp
func testSize(t *testing.T, size int) {
	var b bytes.Buffer
	text := string(bytes.Repeat([]byte("a"), size))
	payload := bytes.Repeat([]byte{1}, size)
	w := bufio.NewWriter(&b)
	err := WritePacket(w, &Packet{
		Text:    text,
		Seq:     1234,
		Payload: payload,
	})
	assert.Nil(t, err)
	// log.Println("size:", size)
	// for i := 0; i < len(b.Bytes()) && i < 255; i++ {
	// 	fmt.Printf("%02x ", b.Bytes()[i])
	// }
	// fmt.Println("")

	var pkt Packet
	r := bufio.NewReader(&b)
	err = ReadPacket(r, &pkt)
	assert.Nil(t, err)
	assert.EqualValues(t, len([]byte(text)), pkt.LengthText)
	assert.EqualValues(t, len(payload), pkt.LengthPayload)
	assert.EqualValues(t, 1234, pkt.Seq)
	assert.EqualValues(t, text, pkt.Text)
	assert.EqualValues(t, payload, pkt.Payload)
}
예제 #14
0
func TestReadStringBytes(t *testing.T) {
	obtained, rest, err := ReadStringBytes([]byte{0xab, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64})
	expected := "Hello World"

	assert.Equal(t, nil, err)
	assert.Equal(t, expected, obtained)
	assert.Equal(t, []byte{}, rest)

	obtained, rest, err = ReadStringBytes([]byte{
		0xd9, 0x21, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31})
	expected = string(bytes.Repeat([]byte{0x31}, 33))

	assert.Equal(t, nil, err)
	assert.Equal(t, expected, obtained)
	assert.Equal(t, []byte{}, rest)

	obtained, rest, err = ReadStringBytes([]byte{
		0xda, 0x01, 0x04, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31})
	expected = string(bytes.Repeat([]byte{0x31}, 260))

	assert.Equal(t, nil, err)
	assert.Equal(t, expected, obtained)
	assert.Equal(t, []byte{}, rest)
}
예제 #15
0
파일: client.go 프로젝트: ghmajx/deblocus
func (c *Client) initialNegotiation() (tun *Conn) {
	var newParams = new(tunParams)
	var err error
	tun, err = c.nego.negotiate(newParams)
	if err != nil {
		if log.V(1) == true || DEBUG {
			log.Errorf("Connection failed %s, Error: %s. Retry after %s",
				c.nego.RemoteName(), err, RETRY_INTERVAL)
		} else {
			log.Errorf("Connection failed %s. Retry after %s",
				c.nego.RemoteName(), RETRY_INTERVAL)
		}
		if strings.Contains(err.Error(), "closed") {
			log.Warningln(string(bytes.Repeat([]byte{'+'}, 30)))
			log.Warningln("Maybe your clock is inaccurate, or your client credential is invalid.")
			log.Warningln(string(bytes.Repeat([]byte{'+'}, 30)))
			os.Exit(2)
		}
		return nil
	}
	c.params = newParams
	c.token = newParams.token

	tun.identifier = c.nego.RemoteName()
	log.Infof("Login to the gateway %s successfully", tun.identifier)
	return
}
예제 #16
0
func TestWriteAndSaveLarge(t *testing.T) {
	const chunkSize = 4096
	const fanout = 64
	chunkStore := &mock.InMemory{}
	blob, err := blobs.Open(chunkStore, &blobs.Manifest{
		Type:      "footype",
		ChunkSize: chunkSize,
		Fanout:    fanout,
	})
	if err != nil {
		t.Fatalf("cannot open blob: %v", err)
	}
	n, err := blob.WriteAt(bytes.Join([][]byte{
		bytes.Repeat([]byte{'x'}, chunkSize),
		bytes.Repeat([]byte{'y'}, chunkSize),
	}, []byte{}), 0)
	if err != nil {
		t.Fatalf("unexpected write error: %v", err)
	}
	if g, e := n, 2*chunkSize; g != e {
		t.Errorf("unexpected write length: %v != %v", g, e)
	}

	saved, err := blob.Save()
	if err != nil {
		t.Fatalf("unexpected error from Save: %v", err)
	}
	if g, e := saved.Root.String(), "9f3f6815c7680f98e00fe9ab5edc85ba3f4ceb657b9562c35b5a865d970ea3270bab8c7aa3162cbaaa966ad84330f34a22aa9539b4c416f858c35c0775482665"; g != e {
		t.Errorf("unexpected key: %q != %q", g, e)
	}
	if g, e := saved.Size, uint64(chunkSize+chunkSize); g != e {
		t.Errorf("unexpected size: %v != %v", g, e)
	}
}
예제 #17
0
파일: table.go 프로젝트: krisrang/goutils
// String prints current table to string.
func (t *Table) String() string {
	if len(t.Data) == 0 {
		return "\n"
	}
	b := new(bytes.Buffer)
	max := func(p *int, v int) {
		if *p < v {
			*p = v
		}
	}
	lengths := make([]int, len(t.Data[0]))
	for _, v := range t.Data {
		for i, cell := range v {
			max(&lengths[i], len(cell))
		}
	}
	spc := []byte{' '}
	for _, v := range t.Data {
		for i, cell := range v {
			b.Write(t.CellConf[i].PadLeft)
			if t.CellConf[i].Align == Right {
				b.Write(bytes.Repeat(spc, lengths[i]-len(cell)))
			}
			b.WriteString(cell)
			if t.CellConf[i].Align == Left && i < len(v)-1 {
				b.Write(bytes.Repeat(spc, lengths[i]-len(cell)))
			}
			b.Write(t.CellConf[i].PadRight)
		}
		b.WriteString("\n")
	}
	return b.String()
}
예제 #18
0
파일: signature.go 프로젝트: decred/dcrd
// NonceRFC6979 generates an ECDSA nonce (`k`) deterministically according to
// RFC 6979. It takes a 32-byte hash as an input and returns 32-byte nonce to
// be used in ECDSA algorithm.
func NonceRFC6979(privkey *big.Int, hash []byte, extra []byte,
	version []byte) *big.Int {
	curve := S256()
	q := curve.Params().N
	x := privkey
	alg := sha256.New

	qlen := q.BitLen()
	holen := alg().Size()
	rolen := (qlen + 7) >> 3
	bx := append(int2octets(x, rolen), bits2octets(hash, curve, rolen)...)
	if len(extra) == 32 {
		bx = append(bx, extra...)
	}
	if len(version) == 16 && len(extra) == 32 {
		bx = append(bx, extra...)
	}
	if len(version) == 16 && len(extra) != 32 {
		bx = append(bx, bytes.Repeat([]byte{0x00}, 32)...)
		bx = append(bx, version...)
	}

	// Step B
	v := bytes.Repeat(oneInitializer, holen)

	// Step C (Go zeroes the all allocated memory)
	k := make([]byte, holen)

	// Step D
	k = mac(alg, k, append(append(v, 0x00), bx...))

	// Step E
	v = mac(alg, k, v)

	// Step F
	k = mac(alg, k, append(append(v, 0x01), bx...))

	// Step G
	v = mac(alg, k, v)

	// Step H
	for {
		// Step H1
		var t []byte

		// Step H2
		for len(t)*8 < qlen {
			v = mac(alg, k, v)
			t = append(t, v...)
		}

		// Step H3
		secret := hashToInt(t, curve)
		if secret.Cmp(one) >= 0 && secret.Cmp(q) < 0 {
			return secret
		}
		k = mac(alg, k, append(v, 0x00))
		v = mac(alg, k, v)
	}
}
예제 #19
0
func TestCorrupt_MissingLastBlock(t *testing.T) {
	buf := new(bytes.Buffer)

	w := NewWriter(buf)

	// First record.
	ww, err := w.Next()
	if err != nil {
		t.Fatal(err)
	}
	if _, err := ww.Write(bytes.Repeat([]byte("0"), blockSize-1024)); err != nil {
		t.Fatalf("write #0: unexpected error: %v", err)
	}

	// Second record.
	ww, err = w.Next()
	if err != nil {
		t.Fatal(err)
	}
	if _, err := ww.Write(bytes.Repeat([]byte("0"), blockSize-headerSize)); err != nil {
		t.Fatalf("write #1: unexpected error: %v", err)
	}

	if err := w.Close(); err != nil {
		t.Fatal(err)
	}

	// Cut the last block.
	b := buf.Bytes()[:blockSize]
	r := NewReader(bytes.NewReader(b), dropper{t}, false, true)

	// First read.
	rr, err := r.Next()
	if err != nil {
		t.Fatal(err)
	}
	n, err := io.Copy(ioutil.Discard, rr)
	if err != nil {
		t.Fatalf("read #0: %v", err)
	}
	if n != blockSize-1024 {
		t.Fatalf("read #0: got %d bytes want %d", n, blockSize-1024)
	}

	// Second read.
	rr, err = r.Next()
	if err != nil {
		t.Fatal(err)
	}
	n, err = io.Copy(ioutil.Discard, rr)
	if err != io.ErrUnexpectedEOF {
		t.Fatalf("read #1: unexpected error: %v", err)
	}

	if _, err := r.Next(); err != io.EOF {
		t.Fatalf("last next: unexpected error: %v", err)
	}
}
예제 #20
0
func TestServe(t *testing.T) {
	defer func(c http.Client) {
		client = c
	}(client)

	tests := []Response{
		{
			Status:     "200 OK",
			StatusCode: http.StatusOK,
			Body:       []byte("ok"),
			header:     http.Header{"foo": []string{"bar"}},
		},
		{
			Status:     "200 OK",
			StatusCode: http.StatusOK,
			Body:       bytes.Repeat([]byte("ok"), 10<<20),
			header:     http.Header{"foo": []string{"bar"}},
		},
		{
			Status:     "200 OK",
			StatusCode: http.StatusOK,
			Body:       bytes.Repeat([]byte("ok"), 10<<20),
			header:     http.Header{},
		},
	}

	for _, tc := range tests {
		mux := http.NewServeMux()
		mux.HandleFunc("/test", func(w http.ResponseWriter, req *http.Request) {
			if len(tc.header) > 0 {
				copyHeader(w.Header(), tc.header)
			}
			if tc.StatusCode != http.StatusOK {
				http.Error(w, "error", tc.StatusCode)
				return
			}
			data := tc.Body
			for len(data) > 0 {
				if len(data) > 128 {
					w.Write(data[:128])
					data = data[128:]
				} else {
					w.Write(data)
					data = nil
				}
			}
		})
		client = http.Client{Transport: transport{mux}}
		resp, err := Serve("/test")
		if err != nil {
			t.Errorf("Serve returned an error: %v", err)
			continue
		}
		if !reflect.DeepEqual(resp, &tc) {
			t.Errorf("Serve = %s; want %s", resp, &tc)
		}
	}
}
예제 #21
0
func TestFrameUnmarshalFCS(t *testing.T) {
	var tests = []struct {
		desc string
		b    []byte
		f    *Frame
		err  error
	}{
		{
			desc: "too short for FCS",
			b:    []byte{1, 2, 3},
			err:  io.ErrUnexpectedEOF,
		},
		{
			desc: "invalid FCS",
			b:    []byte{1, 2, 3, 4},
			err:  ErrInvalidFCS,
		},
		{
			desc: "IPv4, no VLANs",
			b: append(
				append(
					[]byte{
						0, 1, 0, 1, 0, 1,
						1, 0, 1, 0, 1, 0,
						0x08, 0x00,
					},
					bytes.Repeat([]byte{0}, 50)...,
				),
				[]byte{159, 205, 24, 60}...,
			),
			f: &Frame{
				Destination: net.HardwareAddr{0, 1, 0, 1, 0, 1},
				Source:      net.HardwareAddr{1, 0, 1, 0, 1, 0},
				EtherType:   EtherTypeIPv4,
				Payload:     bytes.Repeat([]byte{0}, 50),
			},
		},
	}

	for i, tt := range tests {
		f := new(Frame)
		if err := f.UnmarshalFCS(tt.b); err != nil {
			if want, got := tt.err, err; want != got {
				t.Fatalf("[%02d] test %q, unexpected error: %v != %v",
					i, tt.desc, want, got)
			}

			continue
		}

		if want, got := tt.f, f; !reflect.DeepEqual(want, got) {
			t.Fatalf("[%02d] test %q, unexpected Frame:\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}
예제 #22
0
func TestAppendString(t *testing.T) {
	val := "Hello World"
	obtained := AppendString(nil, val)
	expected := []byte{0xab, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64}

	assert.Equal(t, expected, obtained)

	val = string(bytes.Repeat([]byte{0x31}, 33))
	obtained = AppendString(nil, val)
	expected = []byte{
		0xd9, 0x21, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31}

	val = string(bytes.Repeat([]byte{0x31}, 260))

	obtained = AppendString(nil, val)
	expected = []byte{
		0xda, 0x01, 0x04, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
		0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31}

	assert.Equal(t, expected, obtained)
}
예제 #23
0
// Test using a 64-byte key
func TestK64(t *testing.T) {
	key := bytes.Repeat([]byte{1}, 64)
	nonce := bytes.Repeat([]byte{2}, 16)
	plaintext := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9}
	aData := make([]byte, 24)
	// Compare siv and siv_aead results
	sResult, err := siv.Encrypt(nonce, key, plaintext, [][]byte{aData, nonce})
	if err != nil {
		t.Fatal(err)
	}
	a := New(key)
	aResult := a.Seal(nonce, nonce, plaintext, aData)
	if !bytes.Equal(sResult, aResult) {
		t.Errorf("siv and siv_aead produce different results")
	}
	expectedResult, _ := hex.DecodeString(
		"02020202020202020202020202020202317b316f67c3ad336c01c9a01b4c5e552ba89e966bc4c1ade1")
	if !bytes.Equal(aResult, expectedResult) {
		t.Errorf(hex.EncodeToString(aResult))
	}
	// Verify overhead
	overhead := len(aResult) - len(plaintext) - len(nonce)
	if overhead != a.Overhead() {
		t.Errorf("Overhead() returns a wrong value")
	}
	// Decrypt
	p1, err := a.Open(nil, aResult[:16], aResult[16:], aData)
	if err != nil {
		t.Error(err)
	}
	if !bytes.Equal(plaintext, p1) {
		t.Errorf("wrong plaintext")
	}
	// Decrypt and append
	dst := []byte{0xaa, 0xbb, 0xcc}
	p2, err := a.Open(dst, aResult[:16], aResult[16:], aData)
	if err != nil {
		t.Error(err)
	}
	p2e := append(dst, plaintext...)
	if !bytes.Equal(p2e, p2) {
		t.Errorf("wrong plaintext: %s", hex.EncodeToString(p2))
	}
	// Decrypt corrupt
	aResult[17] = 0
	_, err = a.Open(nil, aResult[:16], aResult[16:], aData)
	if err == nil {
		t.Error("should have failed")
	}
	// Decrypt and append corrupt
	aResult[17] = 0
	_, err = a.Open(dst, aResult[:16], aResult[16:], aData)
	if err == nil {
		t.Error("should have failed")
	}
}
예제 #24
0
파일: runebuf.go 프로젝트: cofyc/readline
func (r *RuneBuffer) Clean() {
	moveToFirst := r.idx
	moveToFirst += len(r.prompt)
	r.w.Write(bytes.Repeat([]byte{'\b'}, moveToFirst))
	length := len(r.buf) + len(r.prompt)

	r.w.Write(bytes.Repeat([]byte{' '}, length))
	r.w.Write(bytes.Repeat([]byte{'\b'}, length))
	r.printPrompt = true
}
예제 #25
0
// TstCreateCreditsOnNewSeries creates a new Series (with a unique ID) and a
// slice of credits locked to the series' address with branch==1 and index==0.
// The new Series will use a 2-of-3 configuration and will be empowered with
// all of its private keys.
func TstCreateCreditsOnNewSeries(t *testing.T, pool *Pool, amounts []int64) (uint32, []credit) {
	masters := []*hdkeychain.ExtendedKey{
		TstCreateMasterKey(t, bytes.Repeat(uint32ToBytes(getUniqueID()), 4)),
		TstCreateMasterKey(t, bytes.Repeat(uint32ToBytes(getUniqueID()), 4)),
		TstCreateMasterKey(t, bytes.Repeat(uint32ToBytes(getUniqueID()), 4)),
	}
	def := TstCreateSeriesDef(t, pool, 2, masters)
	TstCreateSeries(t, pool, []TstSeriesDef{def})
	return def.SeriesID, TstCreateSeriesCredits(t, pool, def.SeriesID, amounts)
}
예제 #26
0
func TestFrameMarshalFCS(t *testing.T) {
	var tests = []struct {
		desc string
		f    *Frame
		b    []byte
		err  error
	}{
		{
			desc: "VLAN priority too large",
			f: &Frame{
				VLAN: []*VLAN{{
					Priority: 8,
				}},
			},
			err: ErrInvalidVLAN,
		},
		{
			desc: "IPv4, no VLANs",
			f: &Frame{
				Destination: net.HardwareAddr{0, 1, 0, 1, 0, 1},
				Source:      net.HardwareAddr{1, 0, 1, 0, 1, 0},
				EtherType:   EtherTypeIPv4,
				Payload:     bytes.Repeat([]byte{0}, 50),
			},
			b: append(
				append(
					[]byte{
						0, 1, 0, 1, 0, 1,
						1, 0, 1, 0, 1, 0,
						0x08, 0x00,
					},
					bytes.Repeat([]byte{0}, 50)...,
				),
				[]byte{159, 205, 24, 60}...,
			),
		},
	}

	for i, tt := range tests {
		b, err := tt.f.MarshalFCS()
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Fatalf("[%02d] test %q, unexpected error: %v != %v",
					i, tt.desc, want, got)
			}

			continue
		}

		if want, got := tt.b, b; !bytes.Equal(want, got) {
			t.Fatalf("[%02d] test %q, unexpected Frame bytes:\n- want: %v\n-  got: %v",
				i, tt.desc, want, got)
		}
	}
}
예제 #27
0
파일: io_test.go 프로젝트: heroku/busl
func TestOverflowingBuffer(t *testing.T) {
	uuid := setup()

	w, _ := NewWriter(uuid)
	w.Write(bytes.Repeat([]byte("0"), 4096))
	w.Write(bytes.Repeat([]byte("1"), 4096))
	w.Write(bytes.Repeat([]byte("2"), 4096))
	w.Write(bytes.Repeat([]byte("3"), 4096))
	w.Write(bytes.Repeat([]byte("4"), 4096))
	w.Write(bytes.Repeat([]byte("5"), 4096))
	w.Write(bytes.Repeat([]byte("6"), 4096))
	w.Write(bytes.Repeat([]byte("7"), 4096))
	w.Write(bytes.Repeat([]byte("A"), 1))

	r, _ := NewReader(uuid)
	defer r.(io.Closer).Close()

	done := make(chan int64)
	go func() {
		n, _ := io.Copy(ioutil.Discard, r)
		done <- n
	}()
	w.Close()
	assert.Equal(t, int64(32769), <-done)
}
예제 #28
0
// makeBeep is a magical function to produce a mono sound signal of the given
// frequency and duration sampled at 8 kHz.
func makeBeep(frequency float64, duration time.Duration) []byte {
	const (
		sample    = 8000
		amplitude = 100
	)
	halfPeriod := int(sample / frequency / 2)
	return bytes.Repeat(
		append(bytes.Repeat([]byte{amplitude}, halfPeriod),
			bytes.Repeat([]byte{0}, halfPeriod)...),
		int(float64(duration)*frequency/float64(time.Second)))
}
예제 #29
0
파일: hgen.go 프로젝트: donlzx/rez
func hgen(a *Asm) {
	h := horizontal{}
	h.zero = a.Data("zero", bytes.Repeat([]byte{0x00}, 16))
	h.hbits = a.Data("hbits", bytes.Repeat([]byte{0x00, 0x00, 0x20, 0x00}, 4))
	h.u8max = a.Data("u8max", bytes.Repeat([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, 2))
	h.genscale(a, 2)
	h.genscale(a, 4)
	h.genscale(a, 8)
	h.genscale(a, 10)
	h.genscale(a, 12)
	h.genscale(a, 0)
}
예제 #30
0
파일: vgen.go 프로젝트: donlzx/rez
func vgen(a *Asm) {
	v := vertical{}
	v.zero = a.Data("zero", bytes.Repeat([]byte{0x00}, 16))
	v.hbits = a.Data("hbits", bytes.Repeat([]byte{0x00, 0x00, 0x20, 0x00}, 4))
	v.genscale(a, 2)
	v.genscale(a, 4)
	v.genscale(a, 6)
	v.genscale(a, 8)
	v.genscale(a, 10)
	v.genscale(a, 12)
	v.genscale(a, 0)
}