golang生成根证书,服务端证书,用于 tls

生成根证书

创建一个 struct 来保存私钥等信息

type CA struct {
	key       *rsa.PrivateKey
	publicKey rsa.PublicKey
	ca        []byte
	keyPerm   []byte
	certPem   []byte
}

生成私钥

func (ca *CA) genPrivateKey() error {
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Println("generate private key err:", err)
		return err
	}
	ca.key = privateKey
	ca.publicKey = privateKey.PublicKey
	return nil
}

生成根证书

func (ca *CA) genCertificate(serviceName string) error {
	maxInt := new(big.Int).Lsh(big.NewInt(1), 128)
	serialNumber, err := rand.Int(rand.Reader, maxInt)
	if err != nil {
		log.Fatalf("failed to generate serial number: %s", err)
		return err
	}
	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"ZZH Co. Ltd"},
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().AddDate(10, 0, 0),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		IsCA:                  true,
		DNSNames:              []string{serviceName},
	}
	ca.ca, err = x509.CreateCertificate(rand.Reader, &template, &template, &ca.publicKey, ca.key)
	if err != nil {
		return err
	}

	ca.keyPerm = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(ca.key)})
	ca.certPem = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.ca})
	return nil
}

NewCA

func NewCA(serviceName string) (*CA, error) {
	ca := &CA{}
	err := ca.genPrivateKey()
	if err != nil {
		return nil, err
	}
	err = ca.genCertificate(serviceName)
	if err != nil {
		return nil, err
	}
	return ca, nil
}

基于根证书生成 服务器 证书

ca, err := private_key.NewCA("example.com")
if err != nil {
    panic(err)
}
// create tls cert
serviceCert, err := tls.X509KeyPair(ca.CertPem(), ca.KeyPerm())
if err != nil {
    panic(err)
}
tlsServiceConfig := &tls.Config{
    Certificates: []tls.Certificate{
        serviceCert,
    },
}

服务端tls监听端口

package main

import (
	"crypto/tls"
	"fmt"
	"github.com/wanmei002/tls/private_key"
	"io"
)

func main() {
	ca, err := private_key.NewCA("example.com")
	if err != nil {
		panic(err)
	}
	// create tls cert
	serviceCert, err := tls.X509KeyPair(ca.CertPem(), ca.KeyPerm())
	if err != nil {
		panic(err)
	}
	tlsServiceConfig := &tls.Config{
		Certificates: []tls.Certificate{
			serviceCert,
		},
	}

	ln, err := tls.Listen("tcp", ":21111", tlsServiceConfig)
	if err != nil {
		panic(err)
	}

	for {
		conn, err := ln.Accept()
		if err != nil {
			panic(err)
		}
		go func() {
			defer conn.Close()
			buf := make([]byte, 1024)
			for {
				_, err := conn.Read(buf)
				if err != nil && err != io.EOF {
					panic(err)
				}
				fmt.Println(string(buf))
				_, err = conn.Write([]byte("Hello"))
				if err != nil {
					panic(err)
				}
			}
		}()
	}
}

客户端 tls 请求

package main

import (
	"crypto/tls"
	"fmt"
	"sync"
)

func main() {
	conn, err := tls.Dial("tcp", "127.0.0.1:21111", &tls.Config{InsecureSkipVerify: true})
	if err != nil {
		panic(err)
	}

	defer conn.Close()
	_, err = conn.Write([]byte("hello world"))
	if err != nil {
		panic(err)
	}
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			buf := make([]byte, 1024)
			_, err = conn.Read(buf)
			if err != nil {
				panic(err)
			}
			fmt.Println(string(buf))
		}
	}()

	wg.Wait()
}

完整代码 https://github.com/wanmei002/tls

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值