/
sign.go
202 lines (182 loc) · 6.1 KB
/
sign.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
// Copyright (C) 2017, 2018, 2019 EGAAS S.A.
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
package crypto
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
crand "crypto/rand"
"encoding/hex"
"fmt"
"math/big"
"github.com/AplaProject/go-apla/packages/consts"
"github.com/AplaProject/go-apla/packages/converter"
log "github.com/sirupsen/logrus"
)
type signProvider int
const (
_ECDSA signProvider = iota
)
// Sign in signing data with private key
func Sign(privateKey, data []byte) ([]byte, error) {
if len(data) == 0 {
log.WithFields(log.Fields{"type": consts.CryptoError}).Debug(ErrSigningEmpty.Error())
}
switch signProv {
case _ECDSA:
return signECDSA(privateKey, data)
default:
return nil, ErrUnknownProvider
}
}
func SignString(privateKeyHex, data string) ([]byte, error) {
privateKey, err := hex.DecodeString(privateKeyHex)
if err != nil {
log.WithFields(log.Fields{"type": consts.ConversionError, "error": err}).Error("decoding private key from hex")
return nil, err
}
return Sign(privateKey, []byte(data))
}
// CheckSign is checking sign
func CheckSign(public, data, signature []byte) (bool, error) {
if len(public) == 0 {
log.WithFields(log.Fields{"type": consts.CryptoError}).Debug(ErrCheckingSignEmpty.Error())
}
switch signProv {
case _ECDSA:
return checkECDSA(public, data, signature)
default:
return false, ErrUnknownProvider
}
}
// JSSignToBytes converts hex signature which has got from the browser to []byte
func JSSignToBytes(in string) ([]byte, error) {
r, s, err := parseSign(in)
if err != nil {
return nil, err
}
return append(converter.FillLeft(r.Bytes()), converter.FillLeft(s.Bytes())...), nil
}
func signECDSA(privateKey, data []byte) (ret []byte, err error) {
var pubkeyCurve elliptic.Curve
switch ellipticSize {
case elliptic256:
pubkeyCurve = elliptic.P256()
default:
log.WithFields(log.Fields{"type": consts.CryptoError}).Fatal(ErrUnsupportedCurveSize.Error())
}
bi := new(big.Int).SetBytes(privateKey)
priv := new(ecdsa.PrivateKey)
priv.PublicKey.Curve = pubkeyCurve
priv.D = bi
signhash, err := Hash(data)
if err != nil {
log.WithFields(log.Fields{"type": consts.CryptoError}).Fatal(ErrHashing.Error())
}
r, s, err := ecdsa.Sign(crand.Reader, priv, signhash)
if err != nil {
return
}
ret = append(converter.FillLeft(r.Bytes()), converter.FillLeft(s.Bytes())...)
return
}
// CheckECDSA checks if forSign has been signed with corresponding to public the private key
func checkECDSA(public, data, signature []byte) (bool, error) {
if len(data) == 0 {
log.WithFields(log.Fields{"type": consts.CryptoError}).Error("data is empty")
return false, fmt.Errorf("invalid parameters len(data) == 0")
}
if len(public) != consts.PubkeySizeLength {
log.WithFields(log.Fields{"size": len(public), "size_match": consts.PubkeySizeLength, "type": consts.SizeDoesNotMatch}).Error("invalid public key")
return false, fmt.Errorf("invalid parameters len(public) = %d", len(public))
}
if len(signature) == 0 {
log.WithFields(log.Fields{"type": consts.CryptoError}).Error("invalid signature")
return false, fmt.Errorf("invalid parameters len(signature) == 0")
}
var pubkeyCurve elliptic.Curve
switch ellipticSize {
case elliptic256:
pubkeyCurve = elliptic.P256()
default:
log.WithFields(log.Fields{"type": consts.CryptoError}).Error(ErrUnsupportedCurveSize.Error())
}
hash, err := Hash(data)
if err != nil {
log.WithFields(log.Fields{"type": consts.CryptoError}).Error(ErrHashing.Error())
}
pubkey := new(ecdsa.PublicKey)
pubkey.Curve = pubkeyCurve
pubkey.X = new(big.Int).SetBytes(public[0:consts.PrivkeyLength])
pubkey.Y = new(big.Int).SetBytes(public[consts.PrivkeyLength:])
r, s, err := parseSign(hex.EncodeToString(signature))
if err != nil {
return false, err
}
verifystatus := ecdsa.Verify(pubkey, hash, r, s)
if !verifystatus {
return false, ErrIncorrectSign
}
return true, nil
}
// parseSign converts the hex signature to r and s big number
func parseSign(sign string) (*big.Int, *big.Int, error) {
var (
binSign []byte
err error
)
// var off int
parse := func(bsign []byte) []byte {
blen := int(bsign[1])
if blen > len(bsign)-2 {
return nil
}
ret := bsign[2 : 2+blen]
if len(ret) > 32 {
ret = ret[len(ret)-32:]
} else if len(ret) < 32 {
ret = append(bytes.Repeat([]byte{0}, 32-len(ret)), ret...)
}
return ret
}
if len(sign) > 128 {
binSign, err = hex.DecodeString(sign)
if err != nil {
log.WithFields(log.Fields{"type": consts.ConversionError, "error": err}).Error("decoding sign from string")
return nil, nil, err
}
left := parse(binSign[2:])
if left == nil || int(binSign[3])+6 > len(binSign) {
log.WithFields(log.Fields{"type": consts.CryptoError}).Error("wrong left parsing")
return nil, nil, fmt.Errorf(`wrong left parsing`)
}
right := parse(binSign[4+binSign[3]:])
if right == nil {
log.WithFields(log.Fields{"type": consts.CryptoError}).Error("wrong right parsing")
return nil, nil, fmt.Errorf(`wrong right parsing`)
}
sign = hex.EncodeToString(append(left, right...))
} else if len(sign) < 128 {
log.WithFields(log.Fields{"size": len(sign), "size_match": 128}).Error("wrong signature size")
return nil, nil, fmt.Errorf(`wrong len of signature %d`, len(sign))
}
all, err := hex.DecodeString(sign[:])
if err != nil {
log.WithFields(log.Fields{"size": len(sign), "size_match": 128}).Error("wrong signature size")
return nil, nil, err
}
return new(big.Int).SetBytes(all[:32]), new(big.Int).SetBytes(all[len(all)-32:]), nil
}