linstrom/storage-new/helpers.go
mstar c269db5b02
Some checks are pending
/ test (push) Waiting to run
Update password hash stuff, totp impl
Move password encryption to argon2id
2025-03-31 17:40:12 +02:00

65 lines
1.2 KiB
Go

package storage
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
// Copied and adjusted from: https://bruinsslot.jp/post/golang-crypto/
func Encrypt(key, data []byte) ([]byte, error) {
// key, salt, err := DeriveKey(key, nil)
// if err != nil {
// return nil, err
// }
//
blockCipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(blockCipher)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
// ciphertext = append(ciphertext, salt...)
return ciphertext, nil
}
func Decrypt(key, data []byte) ([]byte, error) {
// salt, data := data[len(data)-32:], data[:len(data)-32]
// key, _, err := DeriveKey(key, salt)
// if err != nil {
// return nil, err
// }
//
blockCipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(blockCipher)
if err != nil {
return nil, err
}
nonce, ciphertext := data[:gcm.NonceSize()], data[gcm.NonceSize():]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}