golang zip aes base64

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  
", len([]byte(src)), len(b.Bytes()), b.Len()) sEnc := base64.StdEncoding.EncodeToString(b.Bytes()) fmt.Printf("enc=[%s]
", 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]
", sEnc) sDec, err := base64.StdEncoding.DecodeString(sEnc) if err != nil { fmt.Printf("base64 decode failure, error=[%v]
", err) } else { fmt.Printf("dec=[%s]
", 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
", 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) } }

좋은 웹페이지 즐겨찾기