-
Notifications
You must be signed in to change notification settings - Fork 0
/
gosignature.go
83 lines (62 loc) · 1.6 KB
/
gosignature.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
package gosignature
import (
"errors"
"crypto"
"crypto/rsa"
"crypto/x509"
"crypto/rand"
"encoding/pem"
"crypto/sha256"
"encoding/base64"
)
type Signer interface {
Sign(data []byte) ([]byte, error)
}
type rsaPrivateKey struct {
*rsa.PrivateKey
}
func (rsaPrivateKey *rsaPrivateKey) Sign(data []byte) ([]byte, error) {
hash := sha256.New()
hash.Write(data)
hashed := hash.Sum(nil)
return rsa.SignPKCS1v15(rand.Reader, rsaPrivateKey.PrivateKey, crypto.SHA256, hashed)
}
func Generate(privateKey []byte, value []byte) (string, error) {
parser, err := parsePrivateKey(privateKey)
if err != nil {
return "", errors.New("failed to parse the private key.")
}
signed, err := parser.Sign(value)
if err != nil {
return "", errors.New("could not sign the request.")
}
return base64.StdEncoding.EncodeToString(signed), nil
}
func parsePrivateKey(privateKey []byte) (Signer, error) {
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, errors.New("no key was found.")
}
var rawPrivateKey interface{}
switch block.Type {
case "RSA PRIVATE KEY":
rsa, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
rawPrivateKey = rsa
default:
return nil, errors.New("key type not supported [4041].")
}
return newSignerFromPrivateKey(rawPrivateKey)
}
func newSignerFromPrivateKey(rawPrivateKey interface{}) (Signer, error) {
var sshKey Signer
switch privateKeyType := rawPrivateKey.(type) {
case *rsa.PrivateKey:
sshKey = &rsaPrivateKey{privateKeyType}
default:
return nil, errors.New("key type not supported [4041].")
}
return sshKey, nil
}