-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtimelock.go
271 lines (229 loc) · 6.24 KB
/
timelock.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"runtime"
"time"
)
type chainfileLink struct {
PlaintextSeed []byte `json:plaintext_seed`
Hash []byte `json:plaintext_seed`
}
type lockfileLink struct {
EncyptedSeed []byte `json:seed`
VerifyHash []byte `json:verify` // Hash of hash.
}
type lockfileFormat struct {
Meta map[string]string
Chain []lockfileLink
}
type chainfileFormat struct {
Meta map[string]string
Chain []chainfileLink
}
////////////////
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "No command specified.\n")
return
}
cmd := os.Args[1]
os.Args = append(os.Args[0:1], os.Args[2:]...)
switch cmd {
case "benchmark":
rounds := flag.Int("rounds", 200000, "Number of hashes to use in benchmark")
flag.Parse()
_benchmark(*rounds)
case "work":
links := flag.Int("j", 1, "Number of links to compute, e.g. threads")
rounds := flag.Int("rounds", 100000, "Number of hashes to compute for each link")
flag.Parse()
_work(*links, *rounds)
case "concat":
_concat(os.Args[1:])
case "lock":
_lock()
case "unlock":
_unlock()
default:
fmt.Printf("Unknown command: %s\n", cmd)
}
}
func _benchmark(rounds int) {
fmt.Fprintf(os.Stderr, "Available Processors: %d\n", runtime.GOMAXPROCS(0))
fmt.Fprintf(os.Stderr, "Benchmarking hasher...\n")
start := time.Now()
hashChainRounds(rounds, randomBytes(64))
duration := time.Now().Sub(start).Seconds()
hashesPerSecond := float64(rounds) / duration
fmt.Fprintf(os.Stderr, "%d hashes in %f seconds; %.0f hashes per second\n",
rounds, duration, hashesPerSecond)
}
func _work(links int, rounds int) {
fmt.Fprintf(os.Stderr, "Creating a chainfile with %d links, each of %d rounds...\n",
links, rounds)
chain_links := make(chan chainfileLink)
for j := 0; j < links; j++ {
seed := randomBytes(64)
go func() { chain_links <- chainfileLink{seed, hashChainRounds(rounds, seed)} }()
}
chain := make([]chainfileLink, 0)
for j := 0; j < links; j++ {
chain = append(chain, <-chain_links)
}
if err := writeChainfile(os.Stdout, chain); err != nil {
panic(err)
}
}
func _concat(filePaths []string) {
fmt.Fprintf(os.Stderr, "Merging %d chainfiles into one chainfile...\n",
len(filePaths))
mergedChain := make([]chainfileLink, 0)
for _, path := range filePaths {
f, err := os.Open(path)
if err != nil {
panic(err)
}
chainfile := &chainfileFormat{}
json.NewDecoder(f).Decode(chainfile)
for _, chainLink := range chainfile.Chain {
mergedChain = append(mergedChain, chainLink)
}
}
if err := writeChainfile(os.Stdout, mergedChain); err != nil {
panic(err)
}
}
func _lock() {
fmt.Fprintf(os.Stderr, "Converting chainfile to lockfile...\n")
chainfile := &chainfileFormat{}
json.NewDecoder(os.Stdin).Decode(chainfile)
lockedChain := transformChainFileToLockFile(chainfile.Chain)
if err := writeLockfile(os.Stdout, lockedChain); err != nil {
panic(err)
}
}
func _unlock() {
lockfile := &lockfileFormat{}
json.NewDecoder(os.Stdin).Decode(lockfile)
fmt.Fprintf(os.Stderr, "Unlocking lockfile with %d links...\n", len(lockfile.Chain))
var previousHash []byte = nil
for i, chainLink := range lockfile.Chain {
var plaintextSeed []byte
if previousHash == nil {
// This is the first block and thus the EncyptedSeed isn't encrypted
plaintextSeed = chainLink.EncyptedSeed
} else {
// First 32 bytes of hash are the key
block, err := aes.NewCipher(previousHash[0:32])
if err != nil {
panic(err)
}
// Next 16 bytes are the IV
mode := cipher.NewCBCDecrypter(block, previousHash[32:32+aes.BlockSize])
// Decrypt
plaintextSeed = make([]byte, len(chainLink.EncyptedSeed))
mode.CryptBlocks(plaintextSeed, chainLink.EncyptedSeed)
}
fmt.Fprintf(os.Stderr, "Unlocking link #%d\n", i)
previousHash = hashChainVerification(plaintextSeed, chainLink.VerifyHash)
}
fmt.Fprintf(os.Stderr, "Unlock successful. Final hash: %s\n",
base64.URLEncoding.EncodeToString(previousHash))
fmt.Fprintf(os.Stdout, "%s", base64.URLEncoding.EncodeToString(previousHash))
}
func writeChainfile(w io.Writer, chain []chainfileLink) error {
jsonEncoder := json.NewEncoder(w)
err := jsonEncoder.Encode(chainfileFormat{
Meta: map[string]string{
"version": "1",
"hash_algorithm": "sha512-a",
},
Chain: chain,
})
return err
}
func transformChainFileToLockFile(chain []chainfileLink) []lockfileLink {
lockedChain := make([]lockfileLink, len(chain))
for i := 0; i < len(chain); i++ {
var encryptedSeed []byte
if i == 0 {
// First link's seed isn't encrypted
encryptedSeed = chain[i].PlaintextSeed
} else {
// Other links are encrypted with previous link's hash.
previousHash := chain[i-1].Hash
// First 32 bytes of hash are the key
block, err := aes.NewCipher(previousHash[0:32])
if err != nil {
panic(err)
}
// Next 16 bytes are the IV
mode := cipher.NewCBCEncrypter(block, previousHash[32:32+aes.BlockSize])
// Encrypt
encryptedSeed = make([]byte, len(chain[i].PlaintextSeed))
mode.CryptBlocks(encryptedSeed, chain[i].PlaintextSeed)
}
// Verification hash
hasher := sha512.New()
hasher.Write(chain[i].Hash)
verification_hash := hasher.Sum(nil)
lockedChain[i] = lockfileLink{
EncyptedSeed: encryptedSeed,
VerifyHash: verification_hash,
}
}
return lockedChain
}
func writeLockfile(w io.Writer, chain []lockfileLink) error {
jsonEncoder := json.NewEncoder(w)
err := jsonEncoder.Encode(lockfileFormat{
Meta: map[string]string{
"version": "1",
"hash_algorithm": "sha512-a",
"cipher_algorithm": "aes-256-cbc",
},
Chain: chain,
})
return err
}
func hashChainRounds(rounds int, seed []byte) []byte {
for i := 0; i < rounds; i++ {
hasher := sha512.New()
hasher.Write(seed)
seed = hasher.Sum(nil)
}
return seed
}
func hashChainVerification(seed []byte, verify []byte) []byte {
for {
hasher := sha512.New()
hasher.Write(seed)
sum := hasher.Sum(nil)
if bytes.Equal(sum, verify) {
return seed
}
seed = sum
}
}
func randomBytes(c int) []byte {
b := make([]byte, c)
n, err := io.ReadFull(rand.Reader, b)
if n != len(b) || err != nil {
fmt.Println("error:", err)
return nil
}
return b
}
func join(args []string) {
fmt.Printf("")
}