update code

This commit is contained in:
2024-07-04 12:19:44 +07:00
parent dd3a9ebea4
commit 219fa12590
9 changed files with 152 additions and 103 deletions
+2
View File
@@ -23,6 +23,8 @@ var (
LogPath: constants.DefaultLogPath,
LogSaveName: "user",
LogFileExt: "log",
OMVServer: constants.DefaultOMVServer,
SecretKey: constants.DefaultSecretKey,
}
Cfg *ini.File
+63
View File
@@ -10,8 +10,20 @@
package encryption
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"github.com/IceWhaleTech/CasaOS-UserService/pkg/config"
)
var (
// We're using a 32 byte long secret key.
// This is probably something you generate first
// then put into and environment variable.
secretKey string = config.AppInfo.SecretKey
)
func GetMD5ByStr(str string) string {
@@ -19,3 +31,54 @@ func GetMD5ByStr(str string) string {
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
func Encrypt(plaintext string) string {
aes, err := aes.NewCipher([]byte(secretKey))
if err != nil {
panic(err)
}
gcm, err := cipher.NewGCM(aes)
if err != nil {
panic(err)
}
// We need a 12-byte nonce for GCM (modifiable if you use cipher.NewGCMWithNonceSize())
// A nonce should always be randomly generated for every encryption.
nonce := make([]byte, gcm.NonceSize())
_, err = rand.Read(nonce)
if err != nil {
panic(err)
}
// ciphertext here is actually nonce+ciphertext
// So that when we decrypt, just knowing the nonce size
// is enough to separate it from the ciphertext.
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
return string(ciphertext)
}
func Decrypt(ciphertext string) string {
aes, err := aes.NewCipher([]byte(secretKey))
if err != nil {
panic(err)
}
gcm, err := cipher.NewGCM(aes)
if err != nil {
panic(err)
}
// Since we know the ciphertext is actually nonce+ciphertext
// And len(nonce) == NonceSize(). We can separate the two.
nonceSize := gcm.NonceSize()
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, []byte(nonce), []byte(ciphertext), nil)
if err != nil {
panic(err)
}
return string(plaintext)
}