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
/
rsa.go
80 lines (65 loc) · 1.44 KB
/
rsa.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
package sshkey
import (
"bytes"
"crypto"
"crypto/rsa"
"encoding/binary"
"math/big"
)
type rsaPublicKey struct {
pub *rsa.PublicKey
basePublicKey
}
func (r *rsaPublicKey) Length() int {
return r.pub.N.BitLen()
}
func (r *rsaPublicKey) Public() crypto.PublicKey {
return r.pub
}
func marshalRSAPublicKey(k PublicKey) (prefix string, content []byte, err error) {
key, ok := k.Public().(*rsa.PublicKey)
if !ok {
err = ErrUnsupportedKey
return
}
prefix = "ssh-rsa"
buf := bytes.NewBuffer(nil)
buf.Write(encodeByteSlice([]byte(prefix)))
e := make([]byte, 4)
binary.BigEndian.PutUint32(e, uint32(key.E))
buf.Write(encodeByteSlice(bytes.TrimLeft(e, "\x00")))
buf.Write(encodeByteSlice([]byte{0}, key.N.Bytes()))
content = buf.Bytes()
return
}
func unmarshalRSAPublicKey(c []byte, comment string) (*rsaPublicKey, error) {
var alg, exp, mod []byte
alg, c = decodeByteSlice(c)
if alg == nil || string(alg) != "ssh-rsa" {
return nil, ErrMalformedKey
}
exp, c = decodeByteSlice(c)
if exp == nil {
return nil, ErrMalformedKey
}
if len(exp) < 4 {
newExp := make([]byte, 4)
copy(newExp[4-len(exp):4], exp)
exp = newExp
}
mod, _ = decodeByteSlice(c)
if mod == nil {
return nil, ErrMalformedKey
}
key := &rsaPublicKey{
pub: &rsa.PublicKey{
E: int(binary.BigEndian.Uint32(exp)),
N: new(big.Int).SetBytes(mod),
},
basePublicKey: basePublicKey{
keyType: KEY_RSA,
comment: comment,
},
}
return key, nil
}