Newer
Older
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
package jws
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"io/ioutil"
"github.com/zachmann/mytoken/internal/config"
)
// GenerateRSAKeyPair generates an RSA key pair
func GenerateRSAKeyPair() (*rsa.PrivateKey, *rsa.PublicKey) {
privkey, _ := rsa.GenerateKey(rand.Reader, 4096)
return privkey, &privkey.PublicKey
}
// ExportRSAPrivateKeyAsPemStr exports the private key
func ExportRSAPrivateKeyAsPemStr(privkey *rsa.PrivateKey) string {
privkeyBytes := x509.MarshalPKCS1PrivateKey(privkey)
privkeyPem := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privkeyBytes,
},
)
return string(privkeyPem)
}
// ParseRSAPrivateKeyFromPemStr imports an private key
func ParseRSAPrivateKeyFromPemStr(privPEM string) (*rsa.PrivateKey, error) {
block, _ := pem.Decode([]byte(privPEM))
if block == nil {
return nil, errors.New("failed to parse PEM block containing the key")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return priv, nil
}
var privateKey *rsa.PrivateKey
var publicKey *rsa.PublicKey
// GetPrivateKey returns the private key
func GetPrivateKey() *rsa.PrivateKey {
return privateKey
}
// GetPublicKey returns the public key
func GetPublicKey() *rsa.PublicKey {
return publicKey
}
// Init does init
func Init() {
keyFileContent, err := ioutil.ReadFile(config.Get().SigningKeyFile)
if err != nil {
panic(err)
}
sk, err := ParseRSAPrivateKeyFromPemStr(string(keyFileContent))
if err != nil {
panic(err)
}
privateKey = sk
publicKey = &sk.PublicKey
}