增加AES CBC模式工具函数

This commit is contained in:
dushixiang
2021-04-13 23:56:53 +08:00
parent 4f73cd3673
commit 5cee2dd50e
3 changed files with 61 additions and 1 deletions

View File

@ -180,5 +180,5 @@ WantedBy=multi-user.target
systemctl daemon-reload systemctl daemon-reload
systemctl enable next-terminal systemctl enable next-terminal
systemctl start next-terminal systemctl start next-terminal
systemctl staus next-terminal systemctl status next-terminal
``` ```

View File

@ -1,6 +1,7 @@
package utils_test package utils_test
import ( import (
"encoding/base64"
"net" "net"
"testing" "testing"
@ -33,3 +34,20 @@ func TestTcping(t *testing.T) {
_ = conn.Close() _ = conn.Close()
}() }()
} }
func TestAesEncryptCBC(t *testing.T) {
origData := []byte("Hello Next Terminal") // 待加密的数据
key := []byte("qwertyuiopasdfgh") // 加密的密钥
encryptedCBC, err := utils.AesEncryptCBC(origData, key)
assert.NoError(t, err)
assert.Equal(t, "s2xvMRPfZjmttpt+x0MzG9dsWcf1X+h9nt7waLvXpNM=", base64.StdEncoding.EncodeToString(encryptedCBC))
}
func TestAesDecryptCBC(t *testing.T) {
origData, err := base64.StdEncoding.DecodeString("s2xvMRPfZjmttpt+x0MzG9dsWcf1X+h9nt7waLvXpNM=") // 待解密的数据
assert.NoError(t, err)
key := []byte("qwertyuiopasdfgh") // 解密的密钥
decryptCBC, err := utils.AesDecryptCBC(origData, key)
assert.NoError(t, err)
assert.Equal(t, "Hello Next Terminal", string(decryptCBC))
}

View File

@ -2,6 +2,8 @@ package utils
import ( import (
"bytes" "bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5" "crypto/md5"
"database/sql/driver" "database/sql/driver"
"encoding/base64" "encoding/base64"
@ -224,3 +226,43 @@ func Check(f func() error) {
logrus.Error("Received error:", err) logrus.Error("Received error:", err)
} }
} }
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padText...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unPadding := int(origData[length-1])
return origData[:(length - unPadding)]
}
func AesEncryptCBC(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
encrypted := make([]byte, len(origData))
blockMode.CryptBlocks(encrypted, origData)
return encrypted, nil
}
func AesDecryptCBC(encrypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(encrypted))
blockMode.CryptBlocks(origData, encrypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}