当前位置:网站首页>golang zip aes base64

golang zip aes base64

2022-08-09 06:21:00 ggaofeng

1、zip

package main

import (
	"bytes"
	"compress/gzip"
	"encoding/base64"
	"fmt"
)

func main() {
	var b bytes.Buffer
	w := gzip.NewWriter(&b)
	defer w.Close()

	src := "hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world"
	w.Write([]byte(src))
	w.Write([]byte(src))
	w.Write([]byte(src))
	w.Write([]byte(src))
	w.Flush()
	fmt.Printf("size1:%d  size2:%d  size3:%d  \n", len([]byte(src)), len(b.Bytes()), b.Len())
	sEnc := base64.StdEncoding.EncodeToString(b.Bytes())
	fmt.Printf("enc=[%s]\n", sEnc)
}

2、aes

package main

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

func padding(src []byte, blocksize int) []byte {
	padnum := blocksize - len(src)%blocksize
	pad := bytes.Repeat([]byte{byte(padnum)}, padnum)
	return append(src, pad...)
}

func unpadding(src []byte) []byte {
	n := len(src)
	unpadnum := int(src[n-1])
	return src[:n-unpadnum]
}

func encryptAES(src []byte, key []byte) []byte {
	block, _ := aes.NewCipher(key)
	src = padding(src, block.BlockSize())
	blockmode := cipher.NewCBCEncrypter(block, key)
	dst := make([]byte, len(src))
	blockmode.CryptBlocks(dst, src)
	return dst
}

func decryptAES(src []byte, key []byte) []byte {
	block, _ := aes.NewCipher(key)
	blockmode := cipher.NewCBCDecrypter(block, key)
	blockmode.CryptBlocks(src, src)
	src = unpadding(src)
	return src
}

func main() {
	x := []byte("中华人民共和国万岁           世界人民大团结万岁")
	key := []byte("hgfedcba87654321") //16*8=128位,所以是AES128
	x1 := encryptAES(x, key)
	x2 := decryptAES(x1, key)
	fmt.Print(string(x2))
}

3、base64

package main

import (
	"encoding/base64"
	"fmt"
	"os"
	"reflect"
	"strings"
)
func main4() {
	s := "Hello World!"
	b := []byte(s)

	sEnc := base64.StdEncoding.EncodeToString(b)
	fmt.Printf("enc=[%s]\n", sEnc)

	sDec, err := base64.StdEncoding.DecodeString(sEnc)
	if err != nil {
		fmt.Printf("base64 decode failure, error=[%v]\n", err)
	} else {
		fmt.Printf("dec=[%s]\n", sDec)
	}
}
func main3(){
	src := []byte("this is a test string.")
	encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
	encoder.Write(src)
	encoder.Close()
}
func main2(){
	src := []byte("this is a test string.")
	encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)
	encoder.Write(src)
	encoder.Close()
}
func main1() {
	src := "dGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg=="
	reader := strings.NewReader(src)
	decoder := base64.NewDecoder(base64.StdEncoding, reader)

	buf := make([]byte, 10)
	fmt.Printf("%T-----%T=======%s\n", buf, decoder, reflect.TypeOf(buf))
	dst := ""
	for{
		n,err := decoder.Read(buf)
		if n==0{
			println("n=0")
			break
		}
		if err != nil{
			println("err != nil")
			break
		}
		dst += string(buf[:n])
		println(dst)
	}
}

 

原网站

版权声明
本文为[ggaofeng]所创,转载请带上原文链接,感谢
https://blog.csdn.net/ggaofengg/article/details/104713783