1Panel/backend/utils/encrypt/encrypt.go

92 lines
2.2 KiB
Go
Raw Normal View History

2022-08-16 23:30:23 +08:00
package encrypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
2022-09-15 17:15:03 +08:00
"crypto/md5"
2022-08-16 23:30:23 +08:00
"crypto/rand"
"encoding/base64"
2022-09-15 17:15:03 +08:00
"encoding/hex"
2022-08-16 23:30:23 +08:00
"fmt"
"io"
"github.com/1Panel-dev/1Panel/backend/global"
2022-08-16 23:30:23 +08:00
)
func StringEncrypt(text string) (string, error) {
key := global.CONF.Encrypt.Key
pass := []byte(text)
xpass, err := aesEncryptWithSalt([]byte(key), pass)
if err == nil {
pass64 := base64.StdEncoding.EncodeToString(xpass)
return pass64, err
}
return "", err
}
func StringDecrypt(text string) (string, error) {
key := global.CONF.Encrypt.Key
bytesPass, err := base64.StdEncoding.DecodeString(text)
if err != nil {
return "", err
}
var tpass []byte
tpass, err = aesDecryptWithSalt([]byte(key), bytesPass)
if err == nil {
result := string(tpass[:])
return result, err
}
return "", err
}
2022-09-15 17:15:03 +08:00
func Md5(str string) string {
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
2022-08-16 23:30:23 +08:00
func padding(plaintext []byte, blockSize int) []byte {
padding := blockSize - len(plaintext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(plaintext, padtext...)
}
func unPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
func aesEncryptWithSalt(key, plaintext []byte) ([]byte, error) {
plaintext = padding(plaintext, aes.BlockSize)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[0:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cbc := cipher.NewCBCEncrypter(block, iv)
cbc.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return ciphertext, nil
}
func aesDecryptWithSalt(key, ciphertext []byte) ([]byte, error) {
var block cipher.Block
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("iciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
cbc := cipher.NewCBCDecrypter(block, iv)
cbc.CryptBlocks(ciphertext, ciphertext)
ciphertext = unPadding(ciphertext)
return ciphertext, nil
}