This repository has been archived by the owner on Jun 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecdsa.go
100 lines (84 loc) · 1.81 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
package sshkey
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
)
type ecdsaPublicKey struct {
pub *ecdsa.PublicKey
basePublicKey
}
func (k *ecdsaPublicKey) Length() int {
return k.pub.Curve.Params().BitSize
}
func (k *ecdsaPublicKey) Public() crypto.PublicKey {
return k.pub
}
func marshalECDSAPublicKey(k PublicKey) (prefix string, content []byte, err error) {
key, ok := k.Public().(*ecdsa.PublicKey)
if !ok {
err = ErrUnsupportedKey
return
}
var cName string
switch key.Curve.Params().BitSize {
case 256:
cName = "nistp256"
case 384:
cName = "nistp384"
case 521:
cName = "nistp521"
default:
err = ErrUnsupportedKey
return
}
prefix = "ecdsa-sha2-" + cName
buf := bytes.NewBuffer(nil)
buf.Write(encodeByteSlice([]byte(prefix)))
buf.Write(encodeByteSlice([]byte(cName)))
buf.Write(encodeByteSlice(elliptic.Marshal(key.Curve, key.X, key.Y)))
content = buf.Bytes()
return
}
func unmarshalECDSAPublicKey(c []byte, comment string) (*ecdsaPublicKey, error) {
var alg, cName, data []byte
alg, c = decodeByteSlice(c)
if alg == nil || !bytes.HasPrefix(alg, []byte("ecdsa-sha2-")) {
return nil, ErrMalformedKey
}
cName, c = decodeByteSlice(c)
if cName == nil {
return nil, ErrMalformedKey
}
data, c = decodeByteSlice(c)
if data == nil {
return nil, ErrMalformedKey
}
var curve elliptic.Curve
switch string(cName) {
case "nistp256":
curve = elliptic.P256()
case "nistp384":
curve = elliptic.P384()
case "nistp521":
curve = elliptic.P521()
default:
return nil, ErrUnsupportedKey
}
pub := &ecdsa.PublicKey{
Curve: curve,
}
pub.X, pub.Y = elliptic.Unmarshal(curve, data)
if pub.X == nil {
return nil, ErrUnsupportedKey
}
key := &ecdsaPublicKey{
pub: pub,
basePublicKey: basePublicKey{
keyType: KEY_ECDSA,
comment: comment,
},
}
return key, nil
}