golang使用ssl自签证书通信

简介: 版权声明:本文可能为博主原创文章,若标明出处可随便转载。 https://blog.
版权声明:本文可能为博主原创文章,若标明出处可随便转载。 https://blog.csdn.net/Jailman/article/details/79095178

证书是自签名生成的,另外lets encrypt证书免费发放,而且众多大厂都已经开始支持了,不过这只是个例子,无所谓验证有效和权威性了

服务器端

package main

import (
	"crypto/rand"
	"crypto/tls"
	"fmt"
	"log"
	"net"
	"time"
)

func HandleClientConnect(conn net.Conn) {
	defer conn.Close()
	fmt.Println("Receive Connect Request From ", conn.RemoteAddr().String())
	buffer := make([]byte, 1024)
	for {
		len, err := conn.Read(buffer)
		if err != nil {
			log.Println(err.Error())
			break
		}
		fmt.Printf("Receive Data: %s\n", string(buffer[:len]))
		//发送给客户端
		_, err = conn.Write([]byte("服务器收到数据:" + string(buffer[:len])))
		if err != nil {
			break
		}
	}
	fmt.Println("Client " + conn.RemoteAddr().String() + " Connection Closed.....")
}

func main() {
	crt, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		log.Fatalln(err.Error())
	}
	tlsConfig := &tls.Config{}
	tlsConfig.Certificates = []tls.Certificate{crt}
	// Time returns the current time as the number of seconds since the epoch.
	// If Time is nil, TLS uses time.Now.
	tlsConfig.Time = time.Now
	// Rand provides the source of entropy for nonces and RSA blinding.
	// If Rand is nil, TLS uses the cryptographic random reader in package
	// crypto/rand.
	// The Reader must be safe for use by multiple goroutines.
	tlsConfig.Rand = rand.Reader
	l, err := tls.Listen("tcp", "localhost:8888", tlsConfig)
	if err != nil {
		log.Fatalln(err.Error())
	}
	for {
		conn, err := l.Accept()
		if err != nil {
			fmt.Println(err.Error())
			continue
		} else {
			go HandleClientConnect(conn)
		}
	}

}
客户端

package main

import (
	"crypto/tls"
	"fmt"
	"io"
	"time"
	"log"
)

func main() {
	//注意这里要使用证书中包含的主机名称
	tlsConfig := &tls.Config{InsecureSkipVerify: true}
	conn, err := tls.Dial("tcp", "localhost:8888", tlsConfig)
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer conn.Close()
	log.Println("Client Connect To ", conn.RemoteAddr())
	status := conn.ConnectionState()
	fmt.Printf("%#v\n", status)
	buf := make([]byte, 1024)
	ticker := time.NewTicker(1 * time.Millisecond * 500)
	for {
		select {
		case <-ticker.C:
			{
				_, err = io.WriteString(conn, "hello")
				if err != nil {
					log.Fatalln(err.Error())
				}
				len, err := conn.Read(buf)
				if err != nil {
					fmt.Println(err.Error())
				} else {
					fmt.Println("Receive From Server:", string(buf[:len]))
				}
			}
		}
	}

}


目录
相关文章
|
6月前
|
小程序 安全 网络安全
申请免费 SSL 证书为您的小程序加密通信
申请免费 SSL 证书为您的小程序加密通信
137 0
|
1月前
|
安全 Linux 网络安全
Qt SSL/TLS 安全通信类:构建安全网络应用的关键组件
Qt SSL/TLS 安全通信类:构建安全网络应用的关键组件
64 0
|
5月前
|
Go API 开发者
Golang Websocket框架:实时通信的新选择
Golang Websocket框架:实时通信的新选择
EMQ
|
8月前
|
监控 安全 算法
使用 SSL/TLS 加强 MQTT 通信安全
本文将着重介绍 TLS 以及它如何保证 MQTT 通信的完整性、机密性和真实性。
EMQ
509 0
|
11月前
|
网络安全 数据安全/隐私保护 Python
Python3+ssl实现加密通信
Python3+ssl实现加密通信
323 0
|
存储 安全 Go
深入 golang 之 ---goroutine 并发控制与通信
深入 golang 之 ---goroutine 并发控制与通信
|
网络协议 网络安全 开发工具