-
Notifications
You must be signed in to change notification settings - Fork 25
/
key_eddsa.go
78 lines (63 loc) · 1.63 KB
/
key_eddsa.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
package ssh
import (
"fmt"
"errors"
"crypto"
"crypto/ed25519"
"golang.org/x/crypto/ssh"
)
// EdDsa
type KeyEdDsa struct {}
// 包装
func (this KeyEdDsa) Marshal(key crypto.PrivateKey, comment string) (string, []byte, []byte, error) {
k, ok := key.(ed25519.PrivateKey)
if !ok {
return "", nil, nil, errors.New(fmt.Sprintf("unsupported key type %T", key))
}
keyType := ssh.KeyAlgoED25519
pub := make([]byte, ed25519.PublicKeySize)
priv := make([]byte, ed25519.PrivateKeySize)
copy(pub, k[ed25519.PublicKeySize:])
copy(priv, k)
// Marshal public key.
pubKey := struct {
KeyType string
Pub []byte
}{
keyType,
pub,
}
pubkey := ssh.Marshal(pubKey)
// Marshal private key.
prikey := struct {
Pub []byte
Priv []byte
Comment string
}{
pub, priv,
comment,
}
rest := ssh.Marshal(prikey)
return keyType, pubkey, rest, nil
}
// 解析
func (this KeyEdDsa) Parse(rest []byte) (crypto.PrivateKey, string, error) {
key := struct {
Pub []byte
Priv []byte
Comment string
Pad []byte `ssh:"rest"`
}{}
if err := ssh.Unmarshal(rest, &key); err != nil {
return nil, "", err
}
if err := checkOpenSSHKeyPadding(key.Pad); err != nil {
return nil, "", err
}
if len(key.Priv) != ed25519.PrivateKeySize {
return nil, "", errors.New("private key unexpected length")
}
pk := ed25519.PrivateKey(make([]byte, ed25519.PrivateKeySize))
copy(pk, key.Priv)
return pk, key.Comment, nil
}