Пример #1
0
// 如果使用了这个,golang的猜测返回类型的东西会挂掉.请设置输出的内容的类型
// 这个地方返回错误没有什么意义,(调用者无法处理)
func CompressWriteByte(r *http.Request, w http.ResponseWriter, b []byte) {
	acceptEncoding := r.Header.Get("Accept-Encoding")
	switch {
	case strings.Contains(acceptEncoding, "deflate"):
		w.Header().Set("Content-Encoding", "deflate")
		b = kmgCompress.FlateMustCompress(b)
		w.Header().Set("Content-Length", strconv.Itoa(len(b)))
		w.Write(b)
		return
	case strings.Contains(acceptEncoding, "gzip"):
		w.Header().Set("Content-Encoding", "gzip")
		b = kmgCompress.GzipMustCompress(b)
		w.Header().Set("Content-Length", strconv.Itoa(len(b)))
		w.Write(b)
	default:
		w.Header().Set("Content-Length", strconv.Itoa(len(b)))
		w.Write(b)
	}
}
Пример #2
0
/*
先压缩,后加密,
对称加密,正确包含psk的所有功能,
不管是否可以压缩.保证最多会比明文数据增加58个字节.
*/
func CompressAndEncryptBytesEncode(key *[32]byte, data []byte) (output []byte) {
	//先压缩 压缩不了只会多16个字节而已,不需要进行优化
	data = kmgCompress.FlateMustCompress(data)
	//后加密
	cbcIv := kmgRand.MustCryptoRandBytes(16) //此处只会报操作系统不支持的错误.
	block, err := aes.NewCipher((*key)[:])
	if err != nil {
		panic(err) //此处只会由于key长度错误而报错,而此处key长度不会错误.
	}
	blockSize := block.BlockSize()
	paddingSize := blockSize - len(data)%blockSize
	afterCbcSize := paddingSize + len(data)
	output = make([]byte, afterCbcSize+16+16)
	copy(output[:16], cbcIv)
	copy(output[16:], data)
	hashData := sha512.Sum512(data)
	copy(output[len(data)+16:len(data)+16+16], hashData[:16]) //只有前16位,其他的废弃
	copy(output[len(data)+16+16:], bytes.Repeat([]byte{byte(paddingSize)}, paddingSize))
	blockmode := cipher.NewCBCEncrypter(block, cbcIv)
	blockmode.CryptBlocks(output[16:], output[16:])
	return output
}