package utils import ( "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/subtle" "encoding/base64" "errors" "io" "lokideploy/config" "golang.org/x/crypto/argon2" ) func HashPassword(password string) (string, error) { salt := make([]byte, 16) if _, err := rand.Read(salt); err != nil { return "", err } hash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 4, 32) combined := append(salt, hash...) return base64.StdEncoding.EncodeToString(combined), nil } func VerifyPassword(password, hashStr string) bool { combined, err := base64.StdEncoding.DecodeString(hashStr) if err != nil || len(combined) < 16 { return false } salt := combined[:16] hash := combined[16:] newHash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 4, 32) return subtle.ConstantTimeCompare(hash, newHash) == 1 } func Encrypt(plaintext string) (string, error) { key := []byte(config.GetConfig().JWTSecret)[:32] block, err := aes.NewCipher(key) if err != nil { return "", err } gcm, err := cipher.NewGCM(block) if err != nil { return "", err } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return "", err } ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil) return base64.StdEncoding.EncodeToString(ciphertext), nil } func Decrypt(ciphertext string) (string, error) { key := []byte(config.GetConfig().JWTSecret)[:32] data, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return "", err } block, err := aes.NewCipher(key) if err != nil { return "", err } gcm, err := cipher.NewGCM(block) if err != nil { return "", err } if len(data) < gcm.NonceSize() { return "", errors.New("ciphertext too short") } nonce, ciphertextBytes := data[:gcm.NonceSize()], data[gcm.NonceSize():] plaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil) if err != nil { return "", err } return string(plaintext), nil }