• 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

  • 相关阅读:
    京东数据接口:京东数据分析怎么做?
    线程池实现原理
    从键盘任意输出一个整数n,若n不是素数,则计算并输出其所有因子(不包括1),否则输出该数为素数
    半导体分立器件动态测试参数有哪些?纳米软件半导体测试厂商如何助力测试?
    Alist访问主页显示空白解决方法
    HTML 布局
    一元多项式的乘法与加法运算
    SSM框架基于h5的校园兼职招聘系统的设计与实现源码
    java校园共享单车管理系统
    基于图像去雾处理的雾霾污染程度评估(任务书+lunwen+翻译及原文+答辩PPT)
  • 原文地址:https://blog.csdn.net/wanmei002/article/details/139602762