-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtbln.go
240 lines (221 loc) · 5.28 KB
/
tbln.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
// Package tbln reads and writes tbln files.
//
// tbln can contain multiple fields like csv.
// Also, it can include checksum and signature inside.
// TBLN contains three types of lines: data, comments, and extras.
// All rows end with a new line(LF).
// The number of fields in all rows must be the same.
//
// Data begins with "| " and ends with " |". Multiple fields are separated by " | ".
// (Note that the delimiter contains spaces.)
// | fields1 | fields2 | fields3 |
// White space is considered part of a field.
// If "|" is included in the field, "|" must be duplicated.
// | -> || , || -> |||
//
// Comments begin with "# ". Comments are not interpreted.
// # Comments
//
// Extras begin with ";". extras can be interpreted as a header.
// Extras is basically written in the item name: value.
// ; ItemName: Value
// Extras is optional.
// Extras has item names that are interpreted in some special ways.
package tbln
import (
"bytes"
"crypto/sha256"
"crypto/sha512"
"fmt"
"hash"
"regexp"
"strings"
"golang.org/x/crypto/ed25519"
)
// TBLN represents TBLN format data.
// It includes TBLN definition and TBLN rows.
type TBLN struct {
*Definition
RowNum int
Rows [][]string
}
// NewTBLN is create tbln struct.
func NewTBLN() *TBLN {
return &TBLN{
Definition: NewDefinition(),
}
}
// JoinRow makes a Row array a character string.
func JoinRow(row []string) string {
var b strings.Builder
if len(row) == 0 {
return ""
}
_, err := b.WriteString("|")
if err != nil {
return ""
}
for _, column := range row {
_, err = b.WriteString(" ")
if err != nil {
return ""
}
_, err = b.WriteString(escape(column))
if err != nil {
return ""
}
_, err = b.WriteString(" |")
if err != nil {
return ""
}
}
return b.String()
}
// ESCAPE is escape | -> ||
var ESCAPE = regexp.MustCompile(`(\|+)`)
func escape(str string) string {
if strings.Contains(str, "|") {
str = ESCAPE.ReplaceAllString(str, "|$1")
}
return str
}
// SplitRow divides a character string into a row array.
func SplitRow(str string) []string {
if len(str) < 4 {
return nil
}
if str[:2] == "| " {
str = str[2:]
}
if str[len(str)-2:] == " |" {
str = str[0 : len(str)-2]
}
rec := strings.Split(str, " | ")
for i, column := range rec {
rec[i] = unescape(column)
}
return rec
}
// UNESCAPE is unescape || -> |
var UNESCAPE = regexp.MustCompile(`\|(\|+)`)
// unescape vertical bars || -> |
func unescape(str string) string {
if strings.Contains(str, "|") {
str = UNESCAPE.ReplaceAllString(str, "$1")
}
return str
}
// AddRows is Add row to Table.
func (t *TBLN) AddRows(row []string) error {
var err error
t.columnNum, err = checkRow(t.columnNum, row)
if err != nil {
return err
}
t.Rows = append(t.Rows, row)
t.RowNum++
return nil
}
func checkRow(columnNum int, row []string) (int, error) {
if columnNum == 0 {
return len(row), nil
}
if len(row) != columnNum {
return columnNum, fmt.Errorf("invalid column num (%d!=%d) %s", columnNum, len(row), row)
}
return columnNum, nil
}
// Types of supported hashes
const (
SHA256 = "sha256" // import crypto/sha256
SHA512 = "sha512" // import crypto/sha512
)
// SumHash calculated checksum.
func (t *TBLN) SumHash(hashType string) error {
h, err := t.calculateHash(hashType)
if err != nil {
return err
}
if string(t.Hashes[hashType]) != string(h) {
t.Hashes[hashType] = h
// Delete signature
t.Signs = make(map[string]Signature)
}
return nil
}
// calculateHash is returns the calculated checksum.
func (t *TBLN) calculateHash(hashType string) ([]byte, error) {
var hash hash.Hash
switch hashType {
case SHA256:
hash = sha256.New()
case SHA512:
hash = sha512.New()
default:
return nil, fmt.Errorf("not support")
}
w := NewWriter(hash)
if err := w.writeExtraTarget(t.Definition, true); err != nil {
return nil, err
}
for _, row := range t.Rows {
if err := w.WriteRow(row); err != nil {
return nil, err
}
}
return hash.Sum(nil), nil
}
// Sign is returns signature for hash.
func (t *TBLN) Sign(name string, pkey []byte) (map[string]Signature, error) {
if t == nil || t.Definition == nil {
return nil, fmt.Errorf("no algorithm")
}
if t.algorithm != ED25519 {
return nil, fmt.Errorf("unsupported algorithm")
}
if len(pkey) != ed25519.PrivateKeySize {
return nil, fmt.Errorf("bad private key length")
}
t.Signs[name] = Signature{sign: ed25519.Sign(pkey, t.SerializeHash()), algorithm: ED25519}
return t.Signs, nil
}
// VerifySignature returns the boolean value of the signature verification and Verify().
func (t *TBLN) VerifySignature(name string, pubkey []byte) bool {
if t == nil || t.Definition == nil || len(t.Signs) == 0 {
return false
}
if len(pubkey) != ed25519.PublicKeySize {
return false
}
s := t.Signs[name]
if s.algorithm == ED25519 {
x := ed25519.PublicKey(pubkey)
if ed25519.Verify(x, t.SerializeHash(), s.sign) {
return t.Verify()
}
}
return false
}
// Verify returns the boolean value of the hash verification.
func (t *TBLN) Verify() bool {
if len(t.Hashes) == 0 {
return false
}
for name, old := range t.Hashes {
new, err := t.calculateHash(name)
if err != nil {
return false
}
if string(old) != string(new) {
return false
}
}
return true
}
func (t *TBLN) String() string {
buf := new(bytes.Buffer)
if err := WriteAll(buf, t); err != nil {
return ""
}
return buf.String()
}