Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

71 linhas
1.8 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Generate a self-signed X.509 certificate for a TLS server. Outputs to
  5. // 'cert.pem' and 'key.pem' and will overwrite existing files.
  6. package main
  7. import (
  8. "crypto/rsa"
  9. "crypto/rand"
  10. "crypto/x509"
  11. "encoding/pem"
  12. "flag"
  13. "log"
  14. "os"
  15. "time"
  16. )
  17. var hostName *string = flag.String("host", "127.0.0.1", "Hostname to generate a certificate for")
  18. func main() {
  19. flag.Parse()
  20. priv, err := rsa.GenerateKey(rand.Reader, 1024)
  21. if err != nil {
  22. log.Fatalf("failed to generate private key: %s", err)
  23. return
  24. }
  25. now := time.Seconds()
  26. template := x509.Certificate{
  27. SerialNumber: []byte{0},
  28. Subject: x509.Name{
  29. CommonName: *hostName,
  30. Organization: []string{"Acme Co"},
  31. },
  32. NotBefore: time.SecondsToUTC(now - 300),
  33. NotAfter: time.SecondsToUTC(now + 60*60*24*365), // valid for 1 year.
  34. SubjectKeyId: []byte{1, 2, 3, 4},
  35. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  36. }
  37. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
  38. if err != nil {
  39. log.Fatalf("Failed to create certificate: %s", err)
  40. return
  41. }
  42. certOut, err := os.Create("cert.pem")
  43. if err != nil {
  44. log.Fatalf("failed to open cert.pem for writing: %s", err)
  45. return
  46. }
  47. pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  48. certOut.Close()
  49. log.Print("written cert.pem\n")
  50. keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREAT, 0600)
  51. if err != nil {
  52. log.Print("failed to open key.pem for writing:", err)
  53. return
  54. }
  55. pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
  56. keyOut.Close()
  57. log.Print("written key.pem\n")
  58. }