61 lines
1.2 KiB
Go
61 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"errors"
|
|
"io"
|
|
"strings"
|
|
)
|
|
|
|
func encrypt(key, payload string) (string, error) {
|
|
if len(key) == 0 {
|
|
return "", errors.New("key required")
|
|
}
|
|
key = strings.Repeat(key, 32)[:32]
|
|
|
|
block, err := aes.NewCipher([]byte(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
|
|
}
|
|
b := gcm.Seal(nonce, nonce, []byte(payload), nil)
|
|
|
|
return base64.StdEncoding.EncodeToString(b), nil
|
|
}
|
|
|
|
func decrypt(key, payload string) (string, error) {
|
|
if len(key) == 0 {
|
|
return "", errors.New("key required")
|
|
}
|
|
key = strings.Repeat(key, 32)[:32]
|
|
|
|
ciphertext, err := base64.StdEncoding.DecodeString(payload)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
block, err := aes.NewCipher([]byte(key))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
gcm, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(ciphertext) < gcm.NonceSize() {
|
|
return "", errors.New("short ciphertext")
|
|
}
|
|
b, err := gcm.Open(nil, ciphertext[:gcm.NonceSize()], ciphertext[gcm.NonceSize():], nil)
|
|
return string(b), err
|
|
}
|