forked from seehuhn/fortuna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed_test.go
105 lines (98 loc) · 2.53 KB
/
seed_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// seed_test.go - unit tests for seed.go
// Copyright (C) 2013 Jochen Voss <voss@seehuhn.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package fortuna
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestSeedfile(t *testing.T) {
tempDir, err := ioutil.TempDir("", "")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
defer os.RemoveAll(tempDir)
seedFileName := filepath.Join(tempDir, "seed")
// check that the seed file is created
rng, err := NewRNG(seedFileName)
if err != nil {
t.Fatal(err)
}
err = rng.Close()
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(seedFileName); os.IsNotExist(err) {
t.Error("seed file not found")
}
// check that .updateSeedFile() sets the seed and updates the file
rng, err = NewRNG(seedFileName)
if err != nil {
t.Fatal(err)
}
rng.gen.reset()
before, err := ioutil.ReadFile(seedFileName)
if err != nil {
t.Error(err)
}
err = rng.updateSeedFile()
if err != nil {
t.Error(err)
}
after, err := ioutil.ReadFile(seedFileName)
if err != nil {
t.Error(err)
}
// the following would panic if the seed is not reset
rng.RandomData(1)
err = rng.Close()
if err != nil {
t.Error(err)
}
if len(before) != seedFileSize || bytes.Equal(before, after) {
t.Error("seed file not correctly updated")
}
// check that insecure seed files are detected
err = os.Chmod(seedFileName, os.FileMode(0644))
if err != nil {
t.Fatal(err)
}
rng, err = NewRNG(seedFileName)
if err != ErrInsecureSeed {
t.Error("insecure seed file not detected")
}
if rng != nil {
rng.Close()
}
err = os.Chmod(seedFileName, os.FileMode(0600))
if err != nil {
t.Fatal(err)
}
// check that seed files of wrong length are detected
err = ioutil.WriteFile(seedFileName, []byte("Hello"), os.FileMode(0600))
if err != nil {
t.Error(err)
}
rng, err = NewRNG(seedFileName)
if err != ErrCorruptedSeed {
t.Error("corrupted seed file not detected:", err)
}
if rng != nil {
rng.Close()
}
}