aboutsummaryrefslogtreecommitdiff
path: root/crypto.go
blob: bb1dd6a13867b9d1eca3b36a632bbfa3adbaacd7 (plain)
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
package acme

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/base64"
	"encoding/pem"
	"io"
	"io/ioutil"

	"github.com/square/go-jose"
)

func LoadKey(r io.Reader) (*rsa.PrivateKey, error) {
	der, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(der)
	return x509.ParsePKCS1PrivateKey(block.Bytes)
}

func NewKey(w io.Writer, size int) (*rsa.PrivateKey, error) {
	key, err := rsa.GenerateKey(rand.Reader, size)
	if err != nil {
		return nil, err
	}
	block := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	}
	return key, pem.Encode(w, block)
}

func NewCSR(altnames []string, key *rsa.PrivateKey) (string, error) {
	tmpl := x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName: altnames[0],
		},
	}
	if len(altnames) > 1 {
		tmpl.DNSNames = altnames
	}
	der, err := x509.CreateCertificateRequest(rand.Reader, &tmpl, key)
	if err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(der), nil
}

func Thumb(token string, key crypto.PublicKey) (string, error) {
	k := &jose.JsonWebKey{Key: key, Algorithm: "RSA"}
	thumb, err := k.Thumbprint(crypto.SHA256)
	if err != nil {
		return "", err
	}
	return token + "." + base64.RawURLEncoding.EncodeToString(thumb), nil
}