Golang 自签CA证书及双向认证

证书生成

生成CA证书密钥

openssl genrsa -out ca.key 2048

生成CA证书证书

openssl req -new -x509 -days 3650 -key ca.key -out ca.pem

生成服务器证书密钥

openssl genrsa -out server.key 2048

生成服务器证书请求文件

openssl req -new -key server.key -out server.csr

使用自签CA证书给服务器证书签名

openssl x509 -req -sha256 -CA ca.pem -CAkey ca.key -CAcreateserial -days 3650 -in server.csr -out server.pem -extfile server.conf -extensions SAN

生成客户端密钥

openssl genrsa -out client.key 2048

生成客户端证书请求文件

openssl req -new -key client.key -subj "/CN=client" -out client.csr

使用CA证书给客户端证书签名,这里的 extfile.cnf 文件中内容为 extendedKeyUsage=clientAuth

openssl x509 -req -in client.csr -CA ca.pem -CAkey ca.key -CAcreateserial -extfile ./extfile.cnf  -out client.pem -days 5000

到这里所需要的证书就全部生成完毕了, 当然 你也可以使用更简单的方法生成这些证书

certstrap init --common-name "MCENJOY" --expires "20 years"
certstrap request-cert -cn server -ip 127.0.0.1 -domain "localhost"
certstrap sign server --CA MCENJOY
certstrap request-cert -cn client
certstrap sign client --CA MCENJOY

这个工具在

双向认证

客户端代码

package main

import (
	"crypto/tls"
	"crypto/x509"
	"io"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Hello(c *gin.Context) {
	c.JSON(200, gin.H{"code": 1})
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	// Write "Hello, world!" to the response body
	io.WriteString(w, "Hello, world!\n")
}

func main() {
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	r.GET("/hello", Hello)

	// 证书配置
	certPool := x509.NewCertPool()
	ca, err := ioutil.ReadFile("certs/out/MCENJOY.crt")
	if err != nil {
		log.Panic(err)
	}
	ok := certPool.AppendCertsFromPEM(ca)

	if !ok {
		log.Panic(ok)
	}
	tlsConfig := &tls.Config{
		RootCAs:    certPool,
		ClientAuth: tls.RequireAndVerifyClientCert,
	}
	tlsConfig.BuildNameToCertificate()
	s := http.Server{
		Addr:      ":443",
		Handler:   r,
		TLSConfig: tlsConfig,
	}
	log.Fatal(s.ListenAndServeTLS("certs/out/server.crt", "certs/out/server.key"))
}

现在我们访问 https://localhost

客户端代码

package main

import (
	"log"
	"os"

	"github.com/imroc/req/v3"
)

func main() {
	client := req.C()
	//client.SetProxyURL("http://localhost:8880")
	log.Println(os.Getwd())
	client.SetRootCertsFromFile("certs/out/MCENJOY.crt")
	client.SetCertFromFile("certs/out/client.crt", "certs/out/client.key")
	res, err := client.EnableInsecureSkipVerify().R().Get("https://localhost:443/hello")
	if err != nil {
		log.Panic(err)
	}

	log.Println(res.String())
}

尝试进行中间人攻击

无法抓取到数据

广告 广告位招租

评论

  1. enjoy
    Windows Chrome
    2周前
    2022-8-03 12:43:17

    456456456456456456456456

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
小黄脸
上一篇
下一篇