-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.go
83 lines (72 loc) · 1.86 KB
/
convert.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
// Copyright (c) 2017-2019 The Fonero developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package util
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/fonero-project/fnotime/api/v1"
pd "github.com/fonero-project/politeia/politeiad/api/v1"
"github.com/fonero-project/politeia/politeiad/api/v1/identity"
)
// ConvertSignature converts a hex encoded signature to a proper sized byte
// slice.
func ConvertSignature(s string) ([identity.SignatureSize]byte, error) {
sb, err := hex.DecodeString(s)
if err != nil {
return [identity.SignatureSize]byte{}, err
}
if len(sb) != identity.SignatureSize {
return [identity.SignatureSize]byte{},
fmt.Errorf("invalid signature length")
}
var sig [identity.SignatureSize]byte
copy(sig[:], sb)
return sig, nil
}
// ConvertStringToken verifies and converts a string token to a proper sized
// []byte.
func ConvertStringToken(token string) ([]byte, error) {
if len(token) != pd.TokenSize*2 {
return nil, fmt.Errorf("invalid censorship token size")
}
blob, err := hex.DecodeString(token)
if err != nil {
return nil, err
}
return blob, nil
}
// Digest returns the SHA256 of a byte slice.
func Digest(b []byte) []byte {
h := sha256.New()
h.Write(b)
return h.Sum(nil)
}
// IsDigest determines if a string is a valid SHA256 digest.
func IsDigest(digest string) bool {
return v1.RegexpSHA256.MatchString(digest)
}
// ConvertDigest converts a string into a digest.
func ConvertDigest(d string) ([sha256.Size]byte, bool) {
var digest [sha256.Size]byte
if !IsDigest(d) {
return digest, false
}
dd, err := hex.DecodeString(d)
if err != nil {
return digest, false
}
copy(digest[:], dd)
return digest, true
}
// Zero out a byte slice.
func Zero(in []byte) {
if in == nil {
return
}
inlen := len(in)
for i := 0; i < inlen; i++ {
in[i] ^= in[i]
}
}