forked from SSLMate/certspotter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
87 lines (77 loc) · 1.9 KB
/
helpers.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
// Copyright (C) 2017 Opsmate, Inc.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License, v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// This software is distributed WITHOUT A WARRANTY OF ANY KIND.
// See the Mozilla Public License for details.
package cmd
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io/ioutil"
"os"
"software.sslmate.com/src/certspotter/ct"
)
func fileExists(path string) bool {
_, err := os.Lstat(path)
return err == nil
}
func writeFile(filename string, data []byte, perm os.FileMode) error {
tempname := filename + ".new"
if err := ioutil.WriteFile(tempname, data, perm); err != nil {
return err
}
if err := os.Rename(tempname, filename); err != nil {
os.Remove(tempname)
return err
}
return nil
}
func writeJSONFile(filename string, obj interface{}, perm os.FileMode) error {
tempname := filename + ".new"
f, err := os.OpenFile(tempname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
if err := json.NewEncoder(f).Encode(obj); err != nil {
f.Close()
os.Remove(tempname)
return err
}
if err := f.Close(); err != nil {
os.Remove(tempname)
return err
}
if err := os.Rename(tempname, filename); err != nil {
os.Remove(tempname)
return err
}
return nil
}
func readJSONFile(filename string, obj interface{}) error {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
if err = json.Unmarshal(bytes, obj); err != nil {
return err
}
return nil
}
func readSTHFile(filename string) (*ct.SignedTreeHead, error) {
sth := new(ct.SignedTreeHead)
if err := readJSONFile(filename, sth); err != nil {
return nil, err
}
return sth, nil
}
func sha256sum(data []byte) []byte {
sum := sha256.Sum256(data)
return sum[:]
}
func sha256hex(data []byte) string {
return hex.EncodeToString(sha256sum(data))
}