diff options
| author | Martin Kagamino Lehoux <martin@lehoux.net> | 2023-10-24 07:20:10 +0200 |
|---|---|---|
| committer | Martin Kagamino Lehoux <martin@lehoux.net> | 2023-10-24 07:20:29 +0200 |
| commit | 18476c6cba2d5d2bb3ecf3ad136dacbf41d0360e (patch) | |
| tree | a7a958ff7a4bf14ed7f7ee3ffd9c84b7592facbd /auth/crypto.go | |
feat: Extract from other repo
Diffstat (limited to 'auth/crypto.go')
| -rw-r--r-- | auth/crypto.go | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/auth/crypto.go b/auth/crypto.go new file mode 100644 index 0000000..254539f --- /dev/null +++ b/auth/crypto.go @@ -0,0 +1,54 @@ +package auth + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "errors" + + "github.com/martinlehoux/kagamigo/core" +) + +var ( + ErrEncryptedTooShort = errors.New("encrypted text is too short") +) + +func encrypt(secret []byte, plainText string) string { + block, err := aes.NewCipher(secret) + core.Expect(err, "error creating AES cipher") + + aead, err := cipher.NewGCM(block) + core.Expect(err, "error creating AEAD") + + nonce := make([]byte, aead.NonceSize()) + _, err = rand.Read(nonce) + core.Expect(err, "error generating nonce") + + return base64.URLEncoding.EncodeToString(aead.Seal(nonce, nonce, []byte(plainText), nil)) +} + +func decrypt(secret []byte, encryptedText string) (string, error) { + encryptedBytes, err := base64.URLEncoding.DecodeString(encryptedText) + if err != nil { + err = core.Wrap(err, "error decoding base64") + return "", err + } + block, err := aes.NewCipher(secret) + core.Expect(err, "error creating AES cipher") + + aead, err := cipher.NewGCM(block) + core.Expect(err, "error creating AEAD") + + nonceSize := aead.NonceSize() + if len(encryptedBytes) < nonceSize { + return "", ErrEncryptedTooShort + } + nonce, cipherText := encryptedBytes[:nonceSize], encryptedBytes[nonceSize:] + plainBytes, err := aead.Open(nil, nonce, cipherText, nil) + if err != nil { + err = core.Wrap(err, "error decrypting") + return "", err + } + return string(plainBytes), nil +} |
