mirror of
https://github.com/v1k45/pastepass.git
synced 2026-01-08 15:21:56 +00:00
68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package db
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
random "math/rand"
|
|
)
|
|
|
|
func encrypt(text string, key string) ([]byte, error) {
|
|
c, err := aes.NewCipher([]byte(key))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(c)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
nonce := make([]byte, gcm.NonceSize())
|
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return gcm.Seal(nonce, nonce, []byte(text), nil), nil
|
|
}
|
|
|
|
func decrypt(ciphertext []byte, key string) (string, error) {
|
|
c, err := aes.NewCipher([]byte(key))
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to create cipher: %w", err)
|
|
}
|
|
|
|
gcm, err := cipher.NewGCM(c)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to create GCM: %w", err)
|
|
}
|
|
|
|
nonceSize := gcm.NonceSize()
|
|
if len(ciphertext) < nonceSize {
|
|
return "", errors.New("ciphertext too short")
|
|
}
|
|
|
|
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
|
|
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
|
|
if err != nil {
|
|
return "", fmt.Errorf("failed to decrypt: %w", err)
|
|
}
|
|
|
|
return string(plaintext), nil
|
|
}
|
|
|
|
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
|
|
|
const keyLength = 32
|
|
|
|
func randomKey() string {
|
|
b := make([]rune, keyLength)
|
|
for i := range b {
|
|
b[i] = letterRunes[random.Intn(len(letterRunes))]
|
|
}
|
|
return string(b)
|
|
}
|