示例#1
0
func ExampleCipher() {
	key, err := hex.DecodeString("60143a3d7c7137c3622d490e7dbb85859138d198d9c648960e186412a6250722")
	if err != nil {
		panic(err)
	}

	// A nonce should only be used once. Generate it randomly.
	nonce, err := hex.DecodeString("308c92676fa95973")
	if err != nil {
		panic(err)
	}

	c, err := chacha20.New(key, nonce)
	if err != nil {
		panic(err)
	}

	src := []byte("hello I am a secret message")
	dst := make([]byte, len(src))

	c.XORKeyStream(dst, src)

	fmt.Printf("%x\n", dst)
	// Output:
	// a05452ebd981422dcdab2c9cde0d20a03f769e87d3e976ee6d6a11
}
示例#2
0
func TestBadNonceSize(t *testing.T) {
	key := make([]byte, chacha20.KeySize)
	nonce := make([]byte, 3)

	_, err := chacha20.New(key, nonce)

	if err != chacha20.ErrInvalidNonce {
		t.Error("Should have rejected an invalid nonce")
	}
}
示例#3
0
func Chacha20Encrypt(data []byte, key []byte, nonce []byte) (d []byte, err error) {
	if len(key) != 32 {
		return []byte{}, errors.New("Key is 32 bytes")
	}
	e := make([]byte, len(data))
	c, err := chacha20.New(key, nonce)
	if err != nil {
		return []byte{}, err
	}
	c.XORKeyStream(e, data)
	return e, nil
}
示例#4
0
func TestChaCha20(t *testing.T) {
	for i, vector := range testVectors {
		if vector.rounds == 20 {
			t.Logf("Running test vector %d", i)

			key, err := hex.DecodeString(vector.key)
			if err != nil {
				t.Error(err)
			}

			nonce, err := hex.DecodeString(vector.nonce)
			if err != nil {
				t.Error(err)
			}

			c, err := chacha20.New(key, nonce)
			if err != nil {
				t.Error(err)
			}

			expected, err := hex.DecodeString(vector.keyStream)
			if err != nil {
				t.Error(err)
			}

			src := make([]byte, len(expected))
			dst := make([]byte, len(expected))
			c.XORKeyStream(dst, src)

			if !bytes.Equal(expected, dst) {
				t.Errorf("Bad keystream: expected %x, was %x", expected, dst)

				for i, v := range expected {
					if dst[i] != v {
						t.Logf("Mismatch at offset %d: %x vs %x", i, v, dst[i])
						break
					}
				}
			}
		}
	}
}
示例#5
0
func BenchmarkChaCha20(b *testing.B) {
	key := make([]byte, chacha20.KeySize)
	nonce := make([]byte, chacha20.NonceSize)
	c, _ := chacha20.New(key, nonce)
	benchmarkStream(b, c)
}