goext/cryptext/aes.go

69 lines
1.4 KiB
Go
Raw Normal View History

2023-01-29 05:45:29 +01:00
package cryptext
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
2023-01-29 06:02:58 +01:00
"golang.org/x/crypto/scrypt"
2023-01-29 05:45:29 +01:00
"io"
)
// https://stackoverflow.com/a/18819040/1761622
2023-01-29 06:02:58 +01:00
func EncryptAESSimple(password, text []byte) ([]byte, error) {
key, err := scrypt.Key(password, nil, 32768, 8, 1, 32) // this is not 100% correct, rounds too low and salt is missing
if err != nil {
return nil, err
}
2023-01-29 05:45:29 +01:00
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
b := base64.StdEncoding.EncodeToString(text)
ciphertext := make([]byte, aes.BlockSize+len(b))
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
return ciphertext, nil
}
2023-01-29 06:02:58 +01:00
func DecryptAESSimple(password, text []byte) ([]byte, error) {
key, err := scrypt.Key(password, nil, 32768, 8, 1, 32) // this is not 100% correct, rounds too low and salt is missing
if err != nil {
return nil, err
}
2023-01-29 05:45:29 +01:00
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
if len(text) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
iv := text[:aes.BlockSize]
text = text[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(text, text)
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
data, err := base64.StdEncoding.DecodeString(string(text))
if err != nil {
return nil, err
}
2023-01-29 06:02:58 +01:00
2023-01-29 05:45:29 +01:00
return data, nil
}