generateX509

package
v0.0.0-...-48fba18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 9, 2022 License: GPL-3.0 Imports: 14 Imported by: 0

README

为TLS服务器生成自签名X.509证书

一、仅仅生成并使用
func main() {

	_gx := &generateX509.Info{}
	pk, err := _gx.Generate()
	if err != nil {
		log.Fatalln(err)
	}

	s := &http.Server{
		Addr:    "127.0.0.1:1443",
		Handler: nil,
		TLSConfig: &tls.Config{
			Certificates: []tls.Certificate{*pk},
		},
	}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("Hello World!\r\n"))
	})
	log.Println(s.ListenAndServeTLS("", ""))
}
二、生成公私钥文件并使用
func main() {

	_gx := &generateX509.Info{}
	pk, err := _gx.Generate()
	if err != nil {
		log.Fatalln(err)
	}

	crt, key, err := _gx.Pem(pk)
	if err != nil {
		log.Fatalln(err)
	}

	crtF, err := os.Create("/tmp/localhost.crt")
	if err != nil {
		log.Fatalln(err)
	}
	defer crtF.Close()
	keyF, err := os.Create("/tmp/localhost.key")
	if err != nil {
		log.Fatalln(err)
	}
	defer keyF.Close()

	_, _ = crtF.Write(crt)
	_, _ = keyF.Write(key)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("Hello World!\r\n"))
	})
	log.Println(http.ListenAndServeTLS(":1443", "/tmp/localhost.crt", "/tmp/localhost.key", nil))
}

Documentation

Overview

* Example: https://golang.org/src/crypto/tls/generate_cert.go * * Create time: 2020/08/28 * Update time: 2021/09/16

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Info

type Info struct {
	Hostname   string    /* 主机名,默认为本机主机名 */
	ValidFrom  time.Time /* 创建日期,默认为当前时间 */
	ValidFor   int       /* 有效期(天),默认为365天 */
	IsCA       bool      /* 这个证书是否应该是它自己的证书颁发机构,默认为否 */
	RsaBits    int       /* RSA私钥长度,默认为2048 */
	EcdsaCurve string    /* 用于生成密钥的 ECDSA 曲线。 有效值为 P224、P256(推荐)、P384、P521,默认为无 */
	Ed25519Key bool      /* 生成Ed25519私钥,默认为否 */
}

func (*Info) Generate

func (x *Info) Generate() (*tls.Certificate, error)

Generate 生成公私钥密钥对

func (*Info) Pem

func (x *Info) Pem(pk *tls.Certificate) ([]byte, []byte, error)

Pem 转换为pem格式公私钥对

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL