tls.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha1"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "crypto/x509/pkix"
  9. "encoding/base32"
  10. "encoding/pem"
  11. "math/big"
  12. "os"
  13. "path"
  14. "time"
  15. )
  16. const (
  17. tlsRSABits = 2048
  18. tlsName = "syncthing"
  19. )
  20. func loadCert(dir string) (tls.Certificate, error) {
  21. return tls.LoadX509KeyPair(path.Join(dir, "cert.pem"), path.Join(dir, "key.pem"))
  22. }
  23. func certId(bs []byte) string {
  24. hf := sha1.New()
  25. hf.Write(bs)
  26. id := hf.Sum(nil)
  27. return base32.StdEncoding.EncodeToString(id)
  28. }
  29. func newCertificate(dir string) {
  30. priv, err := rsa.GenerateKey(rand.Reader, tlsRSABits)
  31. fatalErr(err)
  32. notBefore := time.Now()
  33. notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
  34. template := x509.Certificate{
  35. SerialNumber: new(big.Int).SetInt64(0),
  36. Subject: pkix.Name{
  37. CommonName: tlsName,
  38. },
  39. NotBefore: notBefore,
  40. NotAfter: notAfter,
  41. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  42. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  43. BasicConstraintsValid: true,
  44. }
  45. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
  46. fatalErr(err)
  47. certOut, err := os.Create(path.Join(dir, "cert.pem"))
  48. fatalErr(err)
  49. pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  50. certOut.Close()
  51. okln("wrote cert.pem")
  52. keyOut, err := os.OpenFile(path.Join(dir, "key.pem"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  53. fatalErr(err)
  54. pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
  55. keyOut.Close()
  56. okln("wrote key.pem")
  57. }