Encrypt
This commit is contained in:
parent
c86c3b40a3
commit
1cdf6cb507
14
encoding.go
14
encoding.go
|
|
@ -66,38 +66,38 @@ func DecryptID(data, salt string) int64 {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 先压缩再加密(适合长文本)
|
// 先压缩再加密(适合长文本)
|
||||||
func Encrypt(plaintext string, key string) (string, error) {
|
func Encrypt(plaintext string, key string) string {
|
||||||
// 1. 压缩
|
// 1. 压缩
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
gz := gzip.NewWriter(&buf)
|
gz := gzip.NewWriter(&buf)
|
||||||
if _, err := gz.Write([]byte(plaintext)); err != nil {
|
if _, err := gz.Write([]byte(plaintext)); err != nil {
|
||||||
return "", err
|
return ""
|
||||||
}
|
}
|
||||||
if err := gz.Close(); err != nil {
|
if err := gz.Close(); err != nil {
|
||||||
return "", err
|
return ""
|
||||||
}
|
}
|
||||||
compressed := buf.Bytes()
|
compressed := buf.Bytes()
|
||||||
|
|
||||||
// 2. 加密(使用AES-GCM)
|
// 2. 加密(使用AES-GCM)
|
||||||
block, err := aes.NewCipher([]byte(Md5(key)))
|
block, err := aes.NewCipher([]byte(Md5(key)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
gcm, err := cipher.NewGCM(block)
|
gcm, err := cipher.NewGCM(block)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
nonce := make([]byte, gcm.NonceSize())
|
nonce := make([]byte, gcm.NonceSize())
|
||||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||||
return "", err
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
ciphertext := gcm.Seal(nonce, nonce, compressed, nil)
|
ciphertext := gcm.Seal(nonce, nonce, compressed, nil)
|
||||||
|
|
||||||
// 使用RawURLEncoding
|
// 使用RawURLEncoding
|
||||||
return base64.RawURLEncoding.EncodeToString(ciphertext), nil
|
return base64.RawURLEncoding.EncodeToString(ciphertext)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Decrypt(encoded string, key string) (string, error) {
|
func Decrypt(encoded string, key string) (string, error) {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue