[🚀] add crypto pkg
This commit is contained in:
71
pkg/crypto/compress.go
Normal file
71
pkg/crypto/compress.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"io"
|
||||
)
|
||||
|
||||
// CompressEncryptor 压缩加密器
|
||||
type CompressEncryptor struct {
|
||||
baseEncryptor Encryptor
|
||||
}
|
||||
|
||||
func NewCompressEncryptor(encryptor Encryptor) *CompressEncryptor {
|
||||
return &CompressEncryptor{baseEncryptor: encryptor}
|
||||
}
|
||||
|
||||
// Encrypt 先压缩后加密
|
||||
func (c *CompressEncryptor) Encrypt(plaintext []byte) ([]byte, error) {
|
||||
// 1. 压缩
|
||||
compressed, err := c.compress(plaintext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 2. 加密
|
||||
return c.baseEncryptor.Encrypt(compressed)
|
||||
}
|
||||
|
||||
// Decrypt 先解密后解压
|
||||
func (c *CompressEncryptor) Decrypt(ciphertext []byte) ([]byte, error) {
|
||||
// 1. 解密
|
||||
compressed, err := c.baseEncryptor.Decrypt(ciphertext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 2. 解压
|
||||
return c.decompress(compressed)
|
||||
}
|
||||
|
||||
func (c *CompressEncryptor) Name() string {
|
||||
return "GZIP-" + c.baseEncryptor.Name()
|
||||
}
|
||||
|
||||
// compress 使用gzip压缩
|
||||
func (c *CompressEncryptor) compress(data []byte) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
writer := gzip.NewWriter(&buf)
|
||||
|
||||
if _, err := writer.Write(data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := writer.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// decompress 使用gzip解压
|
||||
func (c *CompressEncryptor) decompress(data []byte) ([]byte, error) {
|
||||
reader, err := gzip.NewReader(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = reader.Close() }()
|
||||
|
||||
return io.ReadAll(reader)
|
||||
}
|
||||
Reference in New Issue
Block a user