2018-04-11 14:41:50 +01:00
|
|
|
// Copyright (C) 2018 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
2018-10-18 12:10:29 +01:00
|
|
|
package encryption
|
2018-04-11 14:41:50 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"crypto/rand"
|
|
|
|
"io/ioutil"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
func randData(amount int) []byte {
|
|
|
|
buf := make([]byte, amount)
|
|
|
|
_, err := rand.Read(buf)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return buf
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestSecretbox(t *testing.T) {
|
2018-09-26 14:32:23 +01:00
|
|
|
var key Key
|
|
|
|
copy(key[:], randData(KeySize))
|
|
|
|
var firstNonce Nonce
|
|
|
|
copy(firstNonce[:], randData(NonceSize))
|
2018-04-16 01:48:19 +01:00
|
|
|
encrypter, err := NewSecretboxEncrypter(&key, &firstNonce, 4*1024)
|
2018-04-11 14:41:50 +01:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
data := randData(encrypter.InBlockSize() * 10)
|
2018-04-17 14:39:14 +01:00
|
|
|
encrypted := TransformReader(
|
|
|
|
ioutil.NopCloser(bytes.NewReader(data)), encrypter, 0)
|
2018-04-16 01:48:19 +01:00
|
|
|
decrypter, err := NewSecretboxDecrypter(&key, &firstNonce, 4*1024)
|
2018-04-11 14:41:50 +01:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
decrypted := TransformReader(encrypted, decrypter, 0)
|
|
|
|
data2, err := ioutil.ReadAll(decrypted)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if !bytes.Equal(data, data2) {
|
|
|
|
t.Fatalf("encryption/decryption failed")
|
|
|
|
}
|
|
|
|
}
|