1
0

acme.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package acme
  2. import (
  3. "crypto"
  4. "crypto/ecdsa"
  5. "crypto/elliptic"
  6. "crypto/rand"
  7. "io/ioutil"
  8. "log"
  9. "github.com/go-acme/lego/v4/certcrypto"
  10. "github.com/go-acme/lego/v4/certificate"
  11. "github.com/go-acme/lego/v4/challenge/http01"
  12. "github.com/go-acme/lego/v4/lego"
  13. "github.com/go-acme/lego/v4/registration"
  14. )
  15. // You'll need a user or account type that implements acme.User
  16. type MyUser struct {
  17. Email string
  18. Registration *registration.Resource
  19. key crypto.PrivateKey
  20. }
  21. func (u *MyUser) GetEmail() string {
  22. return u.Email
  23. }
  24. func (u MyUser) GetRegistration() *registration.Resource {
  25. return u.Registration
  26. }
  27. func (u *MyUser) GetPrivateKey() crypto.PrivateKey {
  28. return u.key
  29. }
  30. type ACMEHandler struct {
  31. email string
  32. domains []string
  33. }
  34. func NewACME(email string, domains []string) *ACMEHandler {
  35. return &ACMEHandler{
  36. email: email,
  37. domains: domains,
  38. }
  39. }
  40. func (a *ACMEHandler) ObtainCert() {
  41. log.Println("Obtaining certificate...")
  42. // Create a user. New accounts need an email and private key to start.
  43. privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  44. if err != nil {
  45. log.Fatal(err)
  46. }
  47. adminUser := MyUser{
  48. Email: a.email,
  49. key: privateKey,
  50. }
  51. config := lego.NewConfig(&adminUser)
  52. config.CADirURL = "https://acme-staging-v02.api.letsencrypt.org/directory"
  53. config.Certificate.KeyType = certcrypto.RSA2048
  54. client, err := lego.NewClient(config)
  55. if err != nil {
  56. log.Println(err)
  57. }
  58. err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("", "5002"))
  59. if err != nil {
  60. log.Println(err)
  61. }
  62. // New users will need to register
  63. reg, err := client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true})
  64. if err != nil {
  65. log.Println(err)
  66. }
  67. adminUser.Registration = reg
  68. request := certificate.ObtainRequest{
  69. Domains: a.domains,
  70. Bundle: true,
  71. }
  72. certificates, err := client.Certificate.Obtain(request)
  73. if err != nil {
  74. log.Println(err)
  75. }
  76. // Each certificate comes back with the cert bytes, the bytes of the client's
  77. // private key, and a certificate URL. SAVE THESE TO DISK.
  78. err = ioutil.WriteFile("./certs/"+certificates.Domain+".crt", certificates.Certificate, 0777)
  79. err = ioutil.WriteFile("./certs/"+certificates.Domain+".key", certificates.PrivateKey, 0777)
  80. if err != nil {
  81. log.Println(err)
  82. }
  83. // ... all done.
  84. }