文章目录
- 获取KeyLogFile
- 示例代码:
- 1. client
- 2. client
- 3. 效果
获取KeyLogFile
tls.config自带了接口,所以配置的时候只需要打开就行,以客户端为例
keylogfile 是一个 io.Writer 开了这个就自动使用了
keyLogFile, _ := os.OpenFile(keyLogFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
// 2. 配置tls 打开了KeyLogWriter
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
KeyLogWriter: keyLogFile,
}
示例代码:
1. client
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"os"
)
const (
HOST = "localhost"
PORT = "8443"
KEYLOGFILEPATH = "E:\\Martin_Code\\Go\\src\\lesson-03-tls\\02-myTls\\keylogfile-clent.txt"
)
func main() {
if err := tlsWithKeyLog(HOST, KEYLOGFILEPATH); err != nil {
log.Fatalf("tlsWithKeyLog error: %s \n", err)
os.Exit(1)
}
}
func tlsWithKeyLog(url, keyLogFilePath string) error {
// 1. 创建一个文件 已有则覆盖了
keyLogFile, _ := os.OpenFile(keyLogFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
fmt.Fprintf(keyLogFile, "# SSL/TLS secrets log file, generated by go\n")
// 2. 配置tls 打开了KeyLogWriter
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
KeyLogWriter: keyLogFile,
}
// 建立tls连接
conn, err := tls.Dial("tcp", net.JoinHostPort(HOST, PORT), tlsConfig)
if err != nil {
log.Fatalf("客户端Dial()失败:%s", err)
}
defer conn.Close()
conn.Write([]byte("Hello world"))
return nil
}
2. client
package main
import (
"crypto/tls"
"fmt"
"io"
"log"
"net"
"os"
)
const (
CERTFILEPATH = "E:\\Martin_Code\\Go\\src\\lesson-03-tls\\02-myTls\\server.crt"
KEYFILEPATH = "E:\\Martin_Code\\Go\\src\\lesson-03-tls\\02-myTls\\server.key"
KEYLOGFILEPATH = "E:\\Martin_Code\\Go\\src\\lesson-03-tls\\02-myTls\\keylogfile-server.txt"
)
func handleConn(conn net.Conn) {
log.Printf("服务器收到连接:%s", conn.RemoteAddr())
defer conn.Close()
conn.Write([]byte("Hello, 这里是配置了TLS的服务器!\n"))
for {
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
if err == io.EOF {
log.Println("客户端关闭连接")
} else {
log.Printf("服务器读取数据失败:%s", err)
}
return
}
fmt.Printf("服务器收到数据:%s\n", string(buf[:n]))
}
}
func main() {
// 1. 服务器 加载证书和私钥
cert, err := tls.LoadX509KeyPair(CERTFILEPATH, KEYFILEPATH)
if err != nil {
log.Fatalf("服务器加载证书失败:%s", err)
}
log.Println("服务器加载证书成功!")
// 1.1 设置keylog文件
keyLogFile, _ := os.OpenFile(KEYLOGFILEPATH, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
fmt.Fprintf(keyLogFile, "# SSL/TLS secrets log file, generated by go\n")
// 2. 创建TLS配置,并指定证书和私钥
config := &tls.Config{
Certificates: []tls.Certificate{cert},
KeyLogWriter: keyLogFile,
}
log.Println("服务器TLS配置创建成功!")
// 3. 监听
listen, err := tls.Listen("tcp", ":8443", config)
if err != nil {
log.Fatalf("服务器监听失败: %s", err)
}
log.Println("服务器监听成功!")
defer listen.Close()
// 4. 开启Accept
for {
conn, err := listen.Accept()
if err != nil {
log.Printf("服务器Accept()失败:%s", err)
continue
}
// 5. 处理连接
go handleConn(conn)
}
}