Go生成RSA密钥对

golang 原生库生成RSA密钥对,公钥和私钥保存为文件

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"os"
)

func generateRSAKey(privateFile, publicFile string, bits int) error {
	// 生成 RSA 私钥对象
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}

	// 通过x509标准将得到的ras私钥序列化为 ASN.1 的 DER 编码字符串
	x509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)

	// 新建私钥文件
	private, err := os.Create(privateFile)
	if err != nil {
		return err
	}
	defer private.Close()

	// 将数据保存到文件
	err = pem.Encode(private, &pem.Block{
		Type:    "RSA Private Key",
		Headers: map[string]string{},
		Bytes:   x509PrivateKey,
	})
	if err != nil {
		return err
	}

	// X509对公钥编码
	X509PublicKey, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
	if err != nil {
		return err
	}

	// 新建公钥文件
	public, err := os.Create(publicFile)
	if err != nil {
		return err
	}
	defer public.Close()

	// 将数据保存到文件
	err = pem.Encode(public, &pem.Block{
		Type:    "RSA Public Key",
		Headers: map[string]string{},
		Bytes:   X509PublicKey,
	})
	if err != nil {
		return err
	}

	return nil
}

func main() {
	generateRSAKey("./private.key", "./public.key", 4096)
}
发布日期:
分类:Golang

Gin 使用方法

  1. 基础用法:
package main

import (
	"net/http"

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

func main() {
	r := gin.Default()

	r.GET("/", func(c *gin.Context) {
		c.String(200, "Index")
	})

	r.GET("/user/:name", func(c *gin.Context) {
		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	r.POST("/form", func(c *gin.Context) {
		username := c.PostForm("username")
		password := c.DefaultPostForm("password", "000000")

		c.JSON(http.StatusOK, gin.H{
			"username": username,
			"password": password,
		})
	})

	r.POST("/upload", func(c *gin.Context) {
		file, _ := c.FormFile("file")
		// c.SaveUploadedFile(file, dst)
		c.String(http.StatusOK, "%s uploaded!", file.Filename)
	})

	r.Run("0.0.0.0:8800")
}

2. 常用方法

// c.Abort() 
// c.AbortWithError(code int, err error) *Error 
// c.AbortWithStatus(code int) 
// c.AbortWithStatusJSON(code int, jsonObj interface}) 
// c.AsciiJSON(code int, obj interface}) 
// c.Bind(obj interface}) error 
// c.BindHeader(obj interface}) error 
// c.BindJSON(obj interface}) error 
// c.BindQuery(obj interface}) error 
// c.BindUri(obj interface}) error 
// c.BindXML(obj interface}) error 
// c.BindYAML(obj interface}) error 
// c.ClientIP() string 
// c.ContentType() string 
// c.Cookie(name string) (string, error) 
// c.Data(code int, contentType string, data []byte) 
// c.DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) 
// c.Deadline() (deadline time.Time, ok bool) 
// c.DefaultPostForm(key, defaultValue string) string 
// c.DefaultQuery(key, defaultValue string) string 
// c.Done() <-chan struct} 
// c.Err() error 
// c.Error(err error) *Error 
// c.File(filepath string) 
// c.FileAttachment(filepath, filename string) 
// c.FileFromFS(filepath string, fs http.FileSystem) 
// c.FormFile(name string) (*multipart.FileHeader, error) 
// c.FullPath() string 
// c.func bodyAllowedForStatus(status int) bool 
// c.func validateHeader(header string) (clientIP string, valid bool) 
// c.Get(key string) (value interface}, exists bool) 
// c.get(m map[string][]string, key string) (map[string]string, bool) 
// c.GetBool(key string) (b bool) 
// c.GetDuration(key string) (d time.Duration) 
// c.GetFloat64(key string) (f64 float64) 
// c.GetHeader(key string) string 
// c.GetInt(key string) (i int) 
// c.GetInt64(key string) (i64 int64) 
// c.GetPostForm(key string) (string, bool) 
// c.GetPostFormArray(key string) ([]string, bool) 
// c.GetPostFormMap(key string) (map[string]string, bool) 
// c.GetQuery(key string) (string, bool) 
// c.GetQueryArray(key string) ([]string, bool) 
// c.GetQueryMap(key string) (map[string]string, bool) 
// c.GetRawData() ([]byte, error) 
// c.GetString(key string) (s string) 
// c.GetStringMap(key string) (sm map[string]interface}) 
// c.GetStringMapString(key string) (sms map[string]string) 
// c.GetStringMapStringSlice(key string) (smss map[string][]string) 
// c.GetStringSlice(key string) (ss []string) 
// c.GetTime(key string) (t time.Time) 
// c.GetUint(key string) (ui uint) 
// c.GetUint64(key string) (ui64 uint64) 
// c.Handler() HandlerFunc 
// c.HandlerName() string 
// c.HandlerNames() []string 
// c.Header(key, value string) 
// c.HTML(code int, name string, obj interface}) 
// c.IndentedJSON(code int, obj interface}) 
// c.initFormCache() 
// c.initQueryCache() 
// c.IsAborted() bool 
// c.IsWebsocket() bool 
// c.JSON(code int, obj interface}) 
// c.JSONP(code int, obj interface}) 
// c.MultipartForm() (*multipart.Form, error) 
// c.MustBindWith(obj interface}, b binding.Binding) error 
// c.MustGet(key string) interface} 
// c.Negotiate(code int, config Negotiate) 
// c.NegotiateFormat(offered ...string) string 
// c.Next() 
// c.Param(key string) string 
// c.PostForm(key string) string 
// c.PostFormArray(key string) []string 
// c.PostFormMap(key string) map[string]string 
// c.ProtoBuf(code int, obj interface}) 
// c.PureJSON(code int, obj interface}) 
// c.Query(key string) string 
// c.QueryArray(key string) []string 
// c.QueryMap(key string) map[string]string 
// c.Redirect(code int, location string) 
// c.RemoteIP() (net.IP, bool) 
// c.Render(code int, r render.Render) 
// c.requestHeader(key string) string 
// c.SaveUploadedFile(file *multipart.FileHeader, dst string) error 
// c.SecureJSON(code int, obj interface}) 
// c.Set(key string, value interface}) 
// c.SetAccepted(formats ...string) 
// c.SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) 
// c.SetSameSite(samesite http.SameSite) 
// c.ShouldBind(obj interface}) error 
// c.ShouldBindBodyWith(obj interface}, bb binding.BindingBody) (err error) 
// c.ShouldBindHeader(obj interface}) error 
// c.ShouldBindJSON(obj interface}) error 
// c.ShouldBindQuery(obj interface}) error 
// c.ShouldBindUri(obj interface}) error 
// c.ShouldBindWith(obj interface}, b binding.Binding) error 
// c.ShouldBindXML(obj interface}) error 
// c.ShouldBindYAML(obj interface}) error 
// c.SSEvent(name string, message interface}) 
// c.Status(code int) 
// c.Stream(step func(w io.Writer) bool) bool 
// c.String(code int, format string, values ...interface}) 
// c.Value(key interface}) interface} 
// c.XML(code int, obj interface}) 
// c.YAML(code int, obj interface}) 
发布日期:
分类:Golang

Golang网络函数

抓取网页内容

func getHtmlContent(u string, r string) []string {
	resp, err := http.Get(u)
	if err != nil {
		log.Println(err.Error())
		return nil
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK {
		c, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Println(err.Error())
			return nil
		}

		return regexp.MustCompile(`href=".*"`).FindAllString(string(c), -1)
	} else {
		log.Println("Error HTML Code: ", resp.StatusCode)
		return nil
	}
}
发布日期:
分类:Golang

vscode配置golang开发环境

一、安装 VSCode 和 Golang

二、在 go module 模式下加载工具包

mkdir test
cd test
go mod init test

三、配置代理

// set GOPROXY=https://proxy.golang.org
set GOPROXY=https://mirrors.aliyun.com/goproxy/

// GO 1.13+
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy,direct
go env -w GOSUMDB=sum.golang.google.cn

四、下载依赖包

go get github.com/stamblerre/gocode
rename %GOPATH%/gocode.exe %GOPATH%/gocode-gomod.exe

go get github.com/mdempsky/gocode
go get github.com/uudashr/gopkgs/cmd/gopkgs
go get github.com/ramya-rao-a/go-outline
go get github.com/acroca/go-symbols
go get golang.org/x/tools/cmd/guru
go get golang.org/x/tools/cmd/gorename
go get github.com/go-delve/delve/cmd/dlv
go get github.com/rogpeppe/godef
go get golang.org/x/tools/cmd/goimports
go get golang.org/x/lint/golint
go get golang.org/x/tools/gopls

五、优秀的开源项目

https://github.com/golang/go/wiki/Projects

发布日期:
分类:Golang

开发环境镜像设置

一、阿里系镜像

# Composer
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

# npm
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global

# CentOS
curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

# epel
curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

# Pypi
echo "[global]
index-url = https://mirrors.aliyun.com/pypi/simple/

[install]
trusted-host=mirrors.aliyun.com" > ~/.pip/pip.conf

二、其他镜像

# 推荐
go env -w GOPROXY=https://goproxy.cn,direct

# GoProxy Win
# set GOPROXY=https://proxy.golang.org
setx GOPROXY=https://mirrors.aliyun.com/goproxy/

# GoProxy Linux
# export GOPROXY=https://proxy.golang.org
export GOPROXY=https://mirrors.aliyun.com/goproxy/
发布日期:
分类:Golang

Go Module 开发环境配置

一、初始化项目

mkdir go-app
cd go-app
go mod init app

二、设置第三方依赖包

go get github.com/go-sql-driver/mysql@v1.5.0
go get github.com/gin-gonic/gin@v1.6.3
go get github.com/gomodule/redigo/redis@v1.8.3

三、开始编码

package main

import (
	"database/sql"
	"log"

	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func main() {
	databaseInit()
	defer db.Close()
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	r.GET("/", IndexAction)
	r.GET("/user/:name", UserAction)
	r.Run()
}

func databaseInit() {
	var err error
	db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/wordpress")
	if err != nil {
		log.Fatalln(err)
	}
	db.SetMaxIdleConns(500)
	db.SetMaxOpenConns(500)
	err = db.Ping()
	if err != nil {
		log.Fatalln(err)
	}
}

func IndexAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "index"})
}

func UserAction(c *gin.Context) {
	var ID int
	err := db.QueryRow("SELECT ID FROM wp_users WHERE user_login = ?", c.Param("name")).Scan(&ID)
	if err == nil {
		c.String(200, "Hello %d", ID)
	} else {
		c.String(200, "Hello nobody")
	}
}

四、生成本地依赖

go mod vendor

五、运行

go run -mod=vendor main.go
发布日期:
分类:Golang

扫描局域网内80端口

package main

import (
	"fmt"
	"net"
	"strconv"
)

func main() {

	count := 254
	run := make([]chan int, count)

	for index := 0; index < count; index++ {
		run[index] = make(chan int)
	}

	for index := 0; index < count; index++ {
		go func(i int) {
			ip := "192.168.1." + strconv.Itoa(i+1)
			p := scanPort(ip)
			fmt.Println(ip, "\t", p)
			run[i] <- i
		}(index)
	}

	for index := 0; index < count; index++ {
		<-run[index]
	}

}

func scanPort(ip string) bool {
	conn, err := net.Dial("tcp", ip+":80")
	if err != nil {
		return false
	}
	defer conn.Close()
	return true
}
发布日期:
分类:Golang

Golang获取本机的IPV6地址

func getMyIPV6() string {
	s, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, a := range s {
		i := regexp.MustCompile(`(\w+:){7}\w+`).FindString(a.String())
		if strings.Count(i, ":") == 7 {
			return i
		}
	}
	return ""
}
发布日期:
分类:Golang

Go构建DNS请求包

1. DNS请求报文头

[]byte{0x01, 0b100000000, 1, 0, 0, 0}

2. 查询的域名 QNAME

func parseDomain(domain string) []byte {
	var b = []byte{}
	for _, s := range strings.Split(domain, ".") {
		b = append(b, byte(len(s)))
		b = append(b, []byte(s)...)
	}
	b = append(b, byte(0x00))
	return b
}

3. 报文头尾部

[]byte{1, 1}
发布日期:
分类:Golang