/
ecdsa.go
265 lines (211 loc) · 6.24 KB
/
ecdsa.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
package pkcs11wrapper
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"fmt"
"io/ioutil"
"math/big"
)
type EcdsaKey struct {
PubKey *ecdsa.PublicKey
PrivKey *ecdsa.PrivateKey
SKI SubjectKeyIdentifier
}
type SubjectKeyIdentifier struct {
Sha1 string
Sha1Bytes []byte
Sha256 string
Sha256Bytes []byte
}
// SKI returns the subject key identifier of this key.
func (k *EcdsaKey) GenSKI() {
if k.PubKey == nil {
return
}
// Marshall the public key
raw := elliptic.Marshal(k.PubKey.Curve, k.PubKey.X, k.PubKey.Y)
// Hash it
hash := sha256.New()
hash.Write(raw)
k.SKI.Sha256Bytes = hash.Sum(nil)
k.SKI.Sha256 = hex.EncodeToString(k.SKI.Sha256Bytes)
hash = sha1.New()
hash.Write(raw)
k.SKI.Sha1Bytes = hash.Sum(nil)
k.SKI.Sha1 = hex.EncodeToString(k.SKI.Sha1Bytes)
return
}
func (k *EcdsaKey) Generate(namedCurve string) (err error) {
// generate private key
switch namedCurve {
case "P-224":
k.PrivKey, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
case "P-256":
k.PrivKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case "P-384":
k.PrivKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case "P-521":
k.PrivKey, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
default:
k.PrivKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}
// store public key
k.PubKey = &k.PrivKey.PublicKey
return
}
func (k *EcdsaKey) ImportPubKeyFromPubKeyFile(file string) (err error) {
return
}
func (k *EcdsaKey) ImportPubKeyFromCertFile(file string) (err error) {
certFile, err := ioutil.ReadFile(file)
if err != nil {
return
}
certBlock, _ := pem.Decode(certFile)
x509Cert, err := x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return
}
k.PubKey = x509Cert.PublicKey.(*ecdsa.PublicKey)
return
}
func (k *EcdsaKey) ImportPrivKeyFromFile(file string) (err error) {
keyFile, err := ioutil.ReadFile(file)
if err != nil {
return
}
keyBlock, _ := pem.Decode(keyFile)
key, err := x509.ParsePKCS8PrivateKey(keyBlock.Bytes)
if err != nil {
return
}
k.PrivKey = key.(*ecdsa.PrivateKey)
k.PubKey = &k.PrivKey.PublicKey
return
}
/* returns value for CKA_EC_PARAMS */
func GetECParamMarshaled(namedCurve string) (ecParamMarshaled []byte, err error) {
// RFC 5480, 2.1.1.1. Named Curve
//
// secp224r1 OBJECT IDENTIFIER ::= {
// iso(1) identified-organization(3) certicom(132) curve(0) 33 }
//
// secp256r1 OBJECT IDENTIFIER ::= {
// iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
// prime(1) 7 }
//
// secp384r1 OBJECT IDENTIFIER ::= {
// iso(1) identified-organization(3) certicom(132) curve(0) 34 }
//
// secp521r1 OBJECT IDENTIFIER ::= {
// iso(1) identified-organization(3) certicom(132) curve(0) 35 }
//
// NB: secp256r1 is equivalent to prime256v1
ecParamOID := asn1.ObjectIdentifier{}
switch namedCurve {
case "P-224":
ecParamOID = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
case "P-256":
ecParamOID = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
case "P-384":
ecParamOID = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
case "P-521":
ecParamOID = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
}
if len(ecParamOID) == 0 {
err = fmt.Errorf("Error with curve name: %s", namedCurve)
return
}
ecParamMarshaled, err = asn1.Marshal(ecParamOID)
return
}
func (k *EcdsaKey) SignMessage(message string) (signature string, err error) {
// we should always hash the message before signing it
// TODO: make hash function configurable or detected by key size:
// https://www.ietf.org/rfc/rfc4754.txt
// https://tools.ietf.org/html/rfc5656#section-6.2.1
// +----------------+----------------+
// | Curve Size | Hash Algorithm |
// +----------------+----------------+
// | b <= 256 | SHA-256 |
// | | |
// | 256 < b <= 384 | SHA-384 |
// | | |
// | 384 < b | SHA-512 |
// +----------------+----------------+
bs := k.PrivKey.Params().BitSize
var digest []byte
switch {
case bs <= 256:
d := sha256.Sum256([]byte(message))
digest = d[:]
case bs > 256 && bs <= 384:
d := sha512.Sum384([]byte(message))
digest = d[:]
case bs > 384:
d := sha512.Sum512([]byte(message))
digest = d[:]
}
// sign the hash
// if the hash length is greater than the key length,
// then only the first part of the hash that reaches the length of the key will be used
r, s, err := ecdsa.Sign(rand.Reader, k.PrivKey, digest[:])
if err != nil {
return
}
// encode the signature {R, S}
// big.Int.Bytes() will need padding in the case of leading zero bytes
//params := k.PrivKey.Curve.Params()
//curveOrderByteSize := params.P.BitLen() / 8
//rBytes, sBytes := r.Bytes(), s.Bytes()
//signatureBytes := make([]byte, curveOrderByteSize*2)
//copy(signatureBytes[curveOrderByteSize-len(rBytes):], rBytes)
//copy(signatureBytes[curveOrderByteSize*2-len(sBytes):], sBytes)
signatureBytes := r.Bytes()
signatureBytes = append(signatureBytes, s.Bytes()...)
signature = hex.EncodeToString(signatureBytes)
return
}
func (k *EcdsaKey) VerifySignature(message string, signature string) (verified bool) {
signatureBytes, err := hex.DecodeString(signature)
if err != nil {
return
}
// we should always hash the message before signing it
// TODO: detect what hash function to use by key length:
// https://www.ietf.org/rfc/rfc4754.txt
bs := k.PrivKey.Params().BitSize
var digest []byte
switch {
case bs <= 256:
d := sha256.Sum256([]byte(message))
digest = d[:]
case bs > 256 && bs <= 384:
d := sha512.Sum384([]byte(message))
digest = d[:]
case bs > 384:
d := sha512.Sum512([]byte(message))
digest = d[:]
}
// get curve byte size
curveOrderByteSize := k.PubKey.Curve.Params().P.BitLen() / 8
// extract r and s
r, s := new(big.Int), new(big.Int)
r.SetBytes(signatureBytes[:curveOrderByteSize])
s.SetBytes(signatureBytes[curveOrderByteSize:])
verified = ecdsa.Verify(k.PubKey, digest[:], r, s)
return
}
func (k *EcdsaKey) DeriveSharedSecret(anotherPublicKey *ecdsa.PublicKey) (secret []byte, err error) {
x, _ := k.PrivKey.Curve.ScalarMult(anotherPublicKey.X, anotherPublicKey.Y, k.PrivKey.D.Bytes())
secret = x.Bytes()
return
}