keepass-cli/util/crypt.go

68 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-05-15 19:05:42 +00:00
/*
Copyright © 2024 Brian Buller <brian@bullercodeworks.com>
*/
package util
import (
"crypto/aes"
"crypto/cipher"
2024-05-15 20:10:38 +00:00
"crypto/rand"
2024-05-15 19:05:42 +00:00
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
2024-05-15 20:10:38 +00:00
"time"
2024-05-15 19:05:42 +00:00
)
2024-05-15 20:10:38 +00:00
func GenTodayKey() string {
key := []byte(time.Now().Format(fmt.Sprintf("%s%s%s ", time.DateOnly, time.DateOnly, time.DateOnly)))
return hex.EncodeToString(key) //convert to string for saving
}
2024-05-15 19:05:42 +00:00
func Encrypt(key, input string) (string, error) {
2024-05-15 20:10:38 +00:00
btKey, _ := hex.DecodeString(key)
2024-05-15 19:05:42 +00:00
plaintext := []byte(input)
// Create a new Cipher Block from the key
2024-05-15 20:10:38 +00:00
block, err := aes.NewCipher(btKey)
2024-05-15 19:05:42 +00:00
if err != nil {
return "", err
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
2024-05-15 20:10:38 +00:00
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
2024-05-15 19:05:42 +00:00
return "", err
}
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
// Convert to base64
return base64.URLEncoding.EncodeToString(ciphertext), nil
}
func Decrypt(key, input string) (string, error) {
2024-05-15 20:10:38 +00:00
btKey, _ := hex.DecodeString(key)
2024-05-15 19:05:42 +00:00
ciphertext, _ := base64.URLEncoding.DecodeString(input)
2024-05-15 20:10:38 +00:00
block, err := aes.NewCipher(btKey)
2024-05-15 19:05:42 +00:00
if err != nil {
return "", err
}
if len(ciphertext) < aes.BlockSize {
2024-05-15 20:10:38 +00:00
return "", errors.New("ciphertext is too short")
2024-05-15 19:05:42 +00:00
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(ciphertext, ciphertext)
return fmt.Sprintf("%s", ciphertext), nil
}