go demo小结

go常用demo小结

/*
 *args.go 使用os.Args命令行参数输入 另一种flag随后补充
 */
package main

import (
	"fmt"
	"os"
	"reflect"
	"strconv"
)

var Usage = func() {
	fmt.Println("USAGE: calc command [arguments] ...")
	fmt.Println("\nThe commands are:\n\tadd\tAddition of two values.\n\tsqrt\tSquare root of a non-negative value.")
}

func main() {
	args := os.Args
	if args == nil || len(args) < 2 {
		Usage()
		return
	}
	fmt.Println("args[0] = ", args[0])
	fmt.Println("args[1] = ", args[1])

	args2, _ := strconv.Atoi(args[2])
	fmt.Println("args2 = ", args2, reflect.TypeOf(args2))

	if args[1] == "out" {

		a := 5
		fmt.Println("a", a)
	}

	//fmt.Println("a", a) //a :作用域只是在if中
}


/*
 *byte_to_int.go 整形转换成字节 字节转换成整形
 */
package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"reflect"
)

//整形转换成字节
func IntToBytes(n int) []byte {
	tmp := int32(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.BigEndian, &tmp)
	return bytesBuffer.Bytes()
}

//字节转换成整形
func BytesToInt(b []byte) int {
	bytesBuffer := bytes.NewBuffer(b)
	var tmp int32
	binary.Read(bytesBuffer, binary.BigEndian, &tmp)
	return int(tmp)
}

func main() {

	a := 128
	b := IntToBytes(a)
	fmt.Println("b = ", b, len(b), reflect.TypeOf(b))

	var c = []byte{0x00, 0x00, 0x00, 0x08}
	d := BytesToInt(c)
	fmt.Println("d = ", d, reflect.TypeOf(d))

	fmt.Println(c, string(c))

}


/*
 *BytesCombine.go 多个[]byte数组合并成一个[]byte
 */
package main

import (
	"bytes"
	"fmt"
	"reflect"
)

//BytesCombine 多个[]byte数组合并成一个[]byte
func BytesCombine(pBytes ...[]byte) []byte {
	len := len(pBytes)
	s := make([][]byte, len)
	for index := 0; index < len; index++ {
		s[index] = pBytes[index]
	}
	sep := []byte("")
	return bytes.Join(s, sep)
}

//BytesCombine 多个[]byte数组合并成一个[]byte
func PlusBytesCombine(pBytes ...[]byte) []byte {
	return bytes.Join(pBytes, []byte(""))
}

func main() {
	var a = []byte{1, 2, 3, 4}
	var b = []byte{1, 2, 3, 4}
	var c = []byte{1, 2, 3, 4}

	fmt.Println(a, b, c)

	d := BytesCombine(a, b, c)
	fmt.Println(d)

	e := PlusBytesCombine(a, b, c)
	fmt.Println("e =", e, reflect.TypeOf(e))
}


/*
 *zlib.go 压缩 解压[]byte
 */
package main

import (
	"bytes"
	"compress/zlib"
	"fmt"
	"io/ioutil"
)

//压缩byte
func ZipBytes(input []byte) []byte {
	var buf bytes.Buffer
	compressor, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
	if err != nil {
		return input
	}
	compressor.Write(input)
	compressor.Close()
	return buf.Bytes()
}

//解压byte
func UnzipBytes(input []byte) []byte {
	b := bytes.NewReader(input)
	r, err := zlib.NewReader(b)
	defer r.Close()
	if err != nil {
		panic(err)
	}
	data, _ := ioutil.ReadAll(r)
	return data
}

func main() {
	var input = []byte("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKsAAAAgCAYAAABtn4gCAAAI9klEQVR4Xu2cfYxcVRmHn3Pu3Nm6lXa2ta0AYlsgFSGgThMU0W5hGkqApNGARk3cGm3BRN3FYGuCISrBXaNphcSkG2I3hn9gY2gSNWq32AoE1C6KRihFti2QSgvsTmm783HvOa+zM69cSS8Tacsq7n2SX87cj5P7ZvLs2ztnbseICG8HMjIsbxMyMnIoxhja8fJnriuYMNdjOsIVNhd0Y0wBRbxH6nHZ16OdUot2iXNDC3/2mzJtOImOnpHJ2p4Xr13ZkDTYJLHrwRgw4L1gAptIFzt87AoSuzXi/BqJ3KZ/XL1iSGLXd9aOh8u81WRksh5cefmUeFuBgmBABHEeEziwBrUVvCCxayWaSow419MY17zw4eVrz3ls9zbeKjIyWV+4bPkmiVyvCtnqps6Bta2uahJZxQs4jziHxP7fxS1I7B947tJLN5/7xBN9tIeN37yNN0EXME6LecAEGfR/746ZJeuBSy9RUVsiGucxsYPAYuxUzOtlFQEniG8JS+xRaTW+d/+y97P46Sf7yMg4")
	zipInput := ZipBytes(input)
	fmt.Println("input =", len(input))
	fmt.Println("zipIput =", len(zipInput))

	UnZipOut := UnzipBytes(zipInput)
	fmt.Println("UnZipOut =", UnZipOut, "\n", len(UnZipOut))

}


/*
 *base64.go base64编码 解码
 */
 package main

import (
	"encoding/base64"
	"fmt"
	"reflect"
)

func main() {
	input := []byte("hello golang base64 快乐编程http://www.01happy.com +~")

	// 演示base64编码 输入类型:[]byte类型 输出类型:string类型
	encodeString := base64.StdEncoding.EncodeToString(input)
	fmt.Println(encodeString, reflect.TypeOf(encodeString))

	// 对上面的编码结果进行base64解码 输入类型:string类型 输出类型:[]byte类型
	decodeBytes, err := base64.StdEncoding.DecodeString(encodeString)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(decodeBytes), reflect.TypeOf(decodeBytes))
}


/*
 *gen_rsakey.go 产生rsa公私钥
 */
 package main

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

func main() {
	var bits int
	flag.IntVar(&bits, "b", 1024, "密钥长度,默认为1024位")
	if err := GenRsaKey(bits); err != nil {
		log.Fatal("密钥文件生成失败!")
	}
	log.Println("密钥文件生成成功!")
}

func GenRsaKey(bits int) error {
	// 生成私钥文件
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return err
	}
	derStream := x509.MarshalPKCS1PrivateKey(privateKey)
	block := &pem.Block{
		Type:  "私钥",
		Bytes: derStream,
	}
	file, err := os.Create("vgate_private.pem")
	if err != nil {
		return err
	}
	err = pem.Encode(file, block)
	if err != nil {
		return err
	}
	// 生成公钥文件
	publicKey := &privateKey.PublicKey
	derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
	if err != nil {
		return err
	}
	block = &pem.Block{
		Type:  "公钥",
		Bytes: derPkix,
	}
	file, err = os.Create("vgate_public.pem")
	if err != nil {
		return err
	}
	err = pem.Encode(file, block)
	if err != nil {
		return err
	}
	return nil
}


/*
 *rsa.go rsa示例
 */
package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"fmt"
	"io/ioutil"
	"os"

	"reflect"
)

var privateKey, publicKey []byte

func init() {
	var err error
	publicKey, err = ioutil.ReadFile("public.pem")
	if err != nil {
		os.Exit(-1)
	}
	privateKey, err = ioutil.ReadFile("private.pem")
	if err != nil {
		os.Exit(-1)
	}
}

func main() {
	var data []byte
	var err error
	data, err = RsaEncrypt([]byte("hello world"))
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))
	origData, err := RsaDecrypt(data)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(origData))

	src := "test sign"
	signData, err := RsaSign([]byte(src), crypto.MD5)
	if err != nil {
		panic(err)
	}
	sign := hex.EncodeToString(signData)
	fmt.Println("signData type:", reflect.TypeOf(signData))
	fmt.Println("sign type:", reflect.TypeOf(sign))
	fmt.Println(sign)
	fmt.Println(len(sign))
	fmt.Println(len(signData))

	signB, err := hex.DecodeString(sign)

	err = RsaVerify([]byte(src), signB, crypto.MD5)
	if err != nil {
		panic(err)
	}
	fmt.Println("verify success")
}

// Rsa加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

// Rsa解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

//Rsa签名
func RsaSign(src []byte, hash crypto.Hash) ([]byte, error) {
	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	h := hash.New()
	h.Write(src)
	hashed := h.Sum(nil)
	return rsa.SignPKCS1v15(rand.Reader, priv, hash, hashed)
}

//Rsa验签
func RsaVerify(src []byte, sign []byte, hash crypto.Hash) error {
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil
	}
	pub := pubInterface.(*rsa.PublicKey)

	h := hash.New()
	h.Write(src)
	hashed := h.Sum(nil)
	return rsa.VerifyPKCS1v15(pub, hash, hashed, sign)
}


/*
 *aes.go aes示例
 */
 package main

import (
	"crypto/aes"
	"crypto/cipher"
	"fmt"
)

type AesEncrypt struct {
}

//加密字符串 输入类型:string 返回类型:[]byte
func (this *AesEncrypt) Encrypt(key []byte, strMesg string) ([]byte, error) {

	var iv = []byte(key)[:aes.BlockSize]
	encrypted := make([]byte, len(strMesg))
	aesBlockEncrypter, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv)
	aesEncrypter.XORKeyStream(encrypted, []byte(strMesg))
	return encrypted, nil
}

//解密字符串 输入类型:[]byte  返回类型:string
func (this *AesEncrypt) Decrypt(key []byte, src []byte) (strDesc string, err error) {
	defer func() {
		//错误处理
		if e := recover(); e != nil {
			err = e.(error)
		}
	}()

	var iv = []byte(key)[:aes.BlockSize]
	decrypted := make([]byte, len(src))
	var aesBlockDecrypter cipher.Block
	aesBlockDecrypter, err = aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}
	aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv)
	aesDecrypter.XORKeyStream(decrypted, src)
	return string(decrypted), nil
}

func main() {
	aesEnc := AesEncrypt{}
	key := "1234567890123456"

	arrEncrypt, err := aesEnc.Encrypt([]byte(key), "0123456789abcdef123")
	if err != nil {
		fmt.Println(arrEncrypt)
		return
	}
	fmt.Println(arrEncrypt)

	strMsg, err := aesEnc.Decrypt([]byte(key), arrEncrypt)
	if err != nil {
		fmt.Println(arrEncrypt)
		return
	}
	fmt.Println(strMsg)
}


/*
 *md5.go md5示例
 */
package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
)

type MD5Client struct {
}

var MD5 = MD5Client{}

func (this *MD5Client) Encrypt(plantext []byte) []byte {
	result := md5.Sum(plantext)
	return result[:]
}

func main() {
	sum := MD5.Encrypt([]byte(`红薯鸭`))
	fmt.Println("sum is:", sum)

	sumStr := hex.EncodeToString(sum)

	fmt.Println("sumStr is:", sumStr)
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:上身试试 返回首页